GetComponent为空

时间:2015-03-21 09:34:52

标签: c# unity3d nullreferenceexception ngui

我是研究Unity3d游戏开发的新手,我有一个游戏对象,所谓的GameManager,并添加了GameManager.cs。像这样:

enter image description here

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?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我发现根本原因是我没有将MatchItem.cs添加到我的预制件中,现在null异常消失了。