下面是兩個示例方法,除了兩個類引用外,它們都非常相似。即。一個使用FishSettings和FishTileData其他WallSettings和WallTileData。重構兩種類似的方法將數據加載到不同的類
如何編寫單個Method然後調用/引用它所調用的類?我需要一個通用方法嗎?
void Fish(int id, GameObject tile, TileType tileType)
{
FishSettings settings = tile.GetComponent<FishSettings>();
foreach (FishTileData data in DataBase(tileType))
{
if (data.Id == id)
{
settings.Load(data);
break;
}
}
}
void Wall(int id, GameObject tile, TileType tileType)
{
WallSettings settings = tile.GetComponent<WallSettings>();
foreach (WallTileData data in DataBase(tileType))
{
if (data.Id == id)
{
settings.Load(data);
break;
}
}
}
void LoadData(GameObject _newTile, TileData _td)
{
switch (_td.GetTileType()) // This is a virtual Method in the base class : TileData
{
case TileType.Fish:
FishSettings settings = _newTile.GetComponent<FishSettings>();
settings.Load((FishTileData)_td);
break;
case TileType.Wall:
WallSettings settings = _newTile.GetComponent<WallSettings>();
settings.Load((WallTileData)_td);
break;
default:
break;
}
}
Load的定義是怎樣的? –
與您當前的問題完全無關,但它看起來像是從數據庫加載「所有內容」,然後手動搜索以找到您感興趣的一個項目。幾乎總是最好將搜索推入數據庫,並讓* it *更加高效地找到正確的項目。 –
'if(data.Id = id)'應該是'if(data.Id == id)'意味着等於而不是分配值? – peval27