c# - 从另一个脚本访问数组元素时出现 NullReferenceException
问题描述
我有两个对象:Tile和TileGrid,它们有自己的脚本。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() 中初始化字典,它就可以了。然后,当我从另一个脚本访问它时,它会出现同样的错误。我试图在编辑器中更改这些脚本的顺序。
问题的原因是什么,我该如何解决?
解决方案
问题是Start()
在调用之后AttachTile()
。
我应该Awake()
改用。我得到TileGrid对象,Awake()
然后可以在AttachTile()
函数中使用它。
推荐阅读
- php - PHP(Codeigniter 3)会话在Google Cloud Platform中重定向后被破坏,但在Localhost和Cpanel中正常工作
- python - python中向量的大小是(N,1)而不是(N,)
- lua - 如何在lua中将一个表存储到另一个表?
- python - 将 hachoir 库的衍生物安装到 Google Colab 中
- mysql - 在 MySQL 中获取“错误 1452(23000):无法添加或更新子行”
- javascript - 为什么 Google Maps .getCenter() 返回无效坐标?
- javascript - GSAP + AdHelper 模板导致“未定义 lib”
- php - 在 Heroku 上安装 PECL 库
- deep-learning - 使用参数共享计算卷积神经网络中的权重数量
- restframeworkmongoengine - 与同一个django rest框架项目相关的多个mongoDB