[英]GetComponent Null
我剛開始學習Unity3d游戲開發,我有一個GameObject叫做GameManager,並且已將GameManager.cs添加到其中。 像這樣:
的GameManager.cs片段,運行時出現null異常:
public void DisplayTileGrid() {
tiles = new List<MatchItem> ();
for (int x = 0; x < TileData.tileWidth; x++) {
for (int y = 0; y < TileData.tileHeight; y++) {
int type = (int)cells[x, y].cellType;
string spriteName = sprites[type - 1];
GameObject instance = NGUITools.AddChild(grid, matchItemPrefab) as GameObject;
instance.GetComponent<UISprite>().spriteName = spriteName;
instance.transform.localScale = Vector3.one * cellScale;
instance.transform.localPosition = new Vector3(x * cellWidth, y * -cellHeight, 0f);
MatchItem tile = instance.GetComponent<MatchItem>();
tile.target = gameObject;
tile.cell = cells[x, y];
tile.point = new TilePoint(x, y);
tiles.Add(tile);
}
}
}
似乎無法在此處添加我的matchItemPrefab:
GameObject instance = NGUITools.AddChild(grid, matchItemPrefab) as GameObject;
,而instance.GetComponent()返回null。
為什么實例對象沒有MatchItem? 有人可以幫忙嗎?
我發現根本原因是我沒有將MatchItem.cs添加到預制件中,現在null異常消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.