从另一个脚本访问数组元素时出现 NullReferenceException

NullReferenceException when accessing to an element of array from another script

我有两个对象:TileTileGrid,它们有自己的脚本。 TileGrid 可以生成 Tiles 的二维数组。然后我尝试在每个 Tile 的脚本中将每个 Tile 附加到 Tile 周围,因此我的所有 Tile 都将引用它们的 'neighbors'。我用字典。 为此,我编写了一个函数来访问 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
                }
            }
        }
    }
}

GameManager.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() 中初始化字典,它就可以了。然后当我从另一个脚本访问它时,它会出现同样的错误。 我试图在编辑器中更改这些脚本的顺序。

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

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

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