Search code examples
c#unity-game-enginenullreferenceexceptionngui

GetComponent Null


I am new to study Unity3d game development, I have one GameObject so called GameManager, and GameManager.cs has been added to it. Like this:

enter image description here

snip of GameManager.cs, I got null exception when I run:

    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);
        }
    }
}

Seems it is failed to add my matchItemPrefab here:

GameObject instance = NGUITools.AddChild(grid, matchItemPrefab) as GameObject;

, and instance.GetComponent() returned null.

Why doesn't instance object have MatchItem? Can anyone help?


Solution

  • I find that the root cause is I didn't add the MatchItem.cs to my prefab, now the null exception is gone.