int数组's返回未设置为对象实例的对象引用



所以我有一个三维int数组用于我的体素游戏,出于调试目的,我将块中的所有块设置为id 1(dirt(,但在第18行,它给出了错误OBJECT REFERENCE NOT set to AN INSTANCE OF AN OBJECT。我知道这意味着什么,初始值还没有设置。我只是不明白为什么它会返回这个,因为我正在设置初始值。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chunk : MonoBehaviour
{
Mesh mesh = new Mesh();
int[,,] chunkData = new int[4, 64, 4];
// Start is called before the first frame update
void Start()
{
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 64; y++)
{
for (int z = 0; z < 4; z++)
{
chunkData[x, y, z] = 1;// returns error here-----------------------------------------------------------------------------------------------------------------------------------
}
}
}
UpdateChunk();
}
// Update is called once per frame
void Update()
{

}
void UpdateChunk()
{
List<Vector3> vertlist = new List<Vector3>();
List<int> tris = new List<int>();
int currentvert = 0;
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 64; y++)
{
for (int z = 0; z < 4; z++)
{
Vector3[] adjacentBlocks = Block.GetAdjacentChunkBlocks(new Vector3(x, y, z));
for (int i = 0; i < adjacentBlocks.Length; i++)
{
Debug.Log(adjacentBlocks[i]);
}


foreach(Vector3 other in adjacentBlocks)
{
Vector3 result = other - new Vector3(x, y, z);
if (result == Vector3.up && chunkData[(int)other.x, (int)other.y, (int)other.z] == 0 && chunkData[x, y, z] != 0)
{
Debug.Log("upface open");
vertlist.Add(new Vector3(x, y + 1, z));
vertlist.Add(new Vector3(x + 1, y + 1, z));
vertlist.Add(new Vector3(x, y + 1, z + 1));
vertlist.Add(new Vector3(x + 1, y + 1, z + 1));
tris.Add(2 + currentvert);
tris.Add(3 + currentvert);
tris.Add(0 + currentvert);
tris.Add(0 + currentvert);
tris.Add(3 + currentvert);
tris.Add(1 + currentvert); 
}
currentvert += 4;
}
Debug.Log("----------------------------------------------------------");
}
}
}
mesh.vertices = vertlist.ToArray();
mesh.triangles = tris.ToArray();
mesh.RecalculateNormals();
GetComponent<MeshFilter>().mesh = mesh;
}
}

如果在chunkDatanew int[4, 64, 4];时调用Start,它将工作。

我怀疑其他代码正在将chunkData设置为null。

chunkData变成readonly,罪魁祸首就会暴露出来。

最新更新