从另一个脚本访问数组元素时发生NullReferenceException

时间:2018-12-31 03:24:15

标签: c# arrays unity3d nullreferenceexception gameobject

我有两个对象: Tile TileGrid ,它们具有自己的脚本。 TileGrid可以生成2D Tiles数组。然后,我尝试在脚本中为每个图块附加每个图块周围的图块,因此我的所有图块都将引用其“邻居”。我用字典。 为此,我编写了一个函数,该函数正在访问TileGrid的2D 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()中初始化字典,那就可以了。然后,当我从另一个脚本访问它时,它会出现相同的错误。 我试图在编辑器中更改这些脚本的顺序。

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

1 个答案:

答案 0 :(得分:0)

问题在于Start()之后正在呼叫AttachTile()

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