[英]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.