【发布时间】:2022-01-20 00:05:34
【问题描述】:
我不知道为什么,但这是在抛出
NullReferenceException:对象引用未设置为对象的实例
GridSquareController.Update () (在 Assets/Scripts/GridSquareController.cs:53)
代码:
for (int i = 0; i < numOfPrefabs; i++)
{
System.Random rnd = new System.Random();
int squareValue = rnd.Next(1, 6);
gridBehaviour = spawnedPrefabs[i].GetComponent<GridBehaviour>();
gridBehaviour.gridValue = squareValue;
Debug.Log(gridBehaviour.gridValue);
}
我正在尝试在一系列预制件的脚本上设置一个值,我也在这段代码的另一部分初始化。
但是每次我按下激活这个 for 循环的键时,它都会抛出相同的错误。
预制件被初始化的部分:
void SpawnPrefabs()
{
//will create as many prefabs as I specify in the numOfPrefabs variable
if (numOfPrefabs > 0)
{
for (int i = 0; i < numOfPrefabs; i++)
{
GameObject newSpawnedPrefab;
//instantiates a new prefab
newSpawnedPrefab = Instantiate(gridTilePrefab, new Vector3(i, 0, 0), Quaternion.identity);
//parents the new prefab to the transform of the current object (just parenting it really)
newSpawnedPrefab.transform.SetParent(transform);
//adding the prefab to the array
spawnedPrefabs.SetValue(newSpawnedPrefab, i);
}
}
}
这也是我定义变量的地方
// the prefab I am instantiating into the gameworld
public GameObject gridTilePrefab;
public GridBehaviour gridBehaviour;
// an array containing all of the spawned prefabs
public GameObject[] spawnedPrefabs;
// the number of prefabs I want spawned calculated from the length of the array containing the prefabs
public int numOfPrefabs;
public bool Jeremy;
【问题讨论】:
-
这里有很多可能是错误的,但是您没有显示足够多的代码来实际找出您忘记初始化的内容...尝试在调试器中单步执行您的代码并找出您忘记初始化的内容。
-
不要将 new System.Random() 放入循环中。此外,unity 有一个内置的随机选项,可能对您更有效。
-
关于 Unity 随机类的提示听起来很有用,我会研究一下。