這個問題在這里已經有了答案: 什么是 NullReferenceException,我該如何解決? (27 個回答) 2 天前關閉。
我不知道為什么,但這是在拋出
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;
uj5u.com熱心網友回復:
spawnedPrefabs 未啟動。將 spawnedPrefabs= new GameObject[numOfPrefabs] 添加到您的代碼中
void SpawnPrefabs()
{
//will create as many prefabs as I specify in the numOfPrefabs variable
if (numOfPrefabs > 0)
{
spawnedPrefabs= new GameObject[numOfPrefabs] ;
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);
}
}
}
uj5u.com熱心網友回復:
可能是因為這條線。我不確定。
gridBehaviour = spawnedPrefabs[i].GetComponent<GridBehaviour>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385941.html
上一篇:有沒有辦法阻止光線投射穿過物體?
