首页 > 解决方案 > 从另一个脚本访问数组元素时出现 NullReferenceException

问题描述

我有两个对象:TileTileGrid,它们有自己的脚本。TileGrid 可以生成一个二维的 Tiles 数组。然后我试图在每个 Tile 的脚本中将每个 Tile 附加到 Tile 周围,这样我所有的 Tiles 都会引用它们的“邻居”。我用字典。为此,我编写了一个函数来访问 TileGrid 的二维 Tiles 数组。不幸的是,抛出了NullReferenceException 。

TileGridScript.cs

public class TileGridScript : MonoBehaviour
{
    public GameObject[][] tileGrid;
    // Other properties ...
    public void MakeGrid(int width = 64, int height = 64)
    {
        tileGrid = new GameObject[width][];
        for (int x = 0; x < width; x++)
        {
            tileGrid[x] = new GameObject[height];
            for (int y = 0; y < height; y++)
            {
                // !!! Instantiating tiles !!!
                tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
            }
        }
        // !!! Call the function to connect Tiles !!!
        for (int x = 0; x < width; x++)
            for (int y = 0; y < height; y++)
                tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
    }
}

TileScript.cs

public class TileScript : MonoBehaviour
{
    public Dictionary<string, GameObject> connectedTiles;
    // Other properties ...
    private void Start()
    {
        connectedTiles = new Dictionary<string, GameObject>(8);
    }
    public void AttchTile (TileGridScript tileGridScript)
    {
        for (int biasx = -1; biasx < 2; biasx++)
        {
            for (int biasy = -1; biasy < 2; biasy++)
            {

                switch (biasx)
                {
                    case -1: // L
                        switch (biasy)
                        {
                            case -1: // D
                                try
                                {
                                    // !!! Catches the error here !!!
                                    connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy]; 
                                }
                                catch (System.IndexOutOfRangeException) { }
                                break;
                        }
                    // etc for every Tile. P.S. DL means Down and Left.
                    // in this way I add all 8 Tiles around that
                }
            }
        }
    }
}

游戏管理器.cs

public class GameManager : MonoBehaviour
{
    public GameObject tileGridPrefab;
    // Other properties...
    void Start()
    {
        // !!! Here I generate the Tile Grid !!!
        tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
    }
}

我试图在 TileGrid 的脚本中编写这个函数并从中调用它。如果我不在 Start() 中初始化字典,它就可以了。然后,当我从另一个脚本访问它时,它会出现同样的错误。我试图在编辑器中更改这些脚本的顺序。

问题的原因是什么,我该如何解决?

标签: c#arraysunity3dnullreferenceexceptiongameobject

解决方案


问题是Start()在调用之后AttachTile()

我应该Awake()改用。我得到TileGrid对象,Awake()然后可以在AttachTile()函数中使用它。


推荐阅读