Mesh set to new mesh but "not initialized"

I’m trying to create an array of meshes, then set the vertice and triangle values for each. However, when trying to set these, I get the terrible “NullReferenceException: Object reference not set to an instance of an object” error. Below is my code:

Mesh[] tempCubeMeshArr; // Global variable

private void Start() {
       ...
        tempCubeMeshArr = new Mesh[chunkSize * chunkSize * chunkSize];
        for (int meshIndex = 0; meshIndex < tempCubeMeshArr.Length; meshIndex++) {
            tempCubeMeshArr[meshIndex] = new Mesh();
       }
       ...
}

void function(){
       ...
       // This is where null error is shown
       tempCubeMeshArr[cubeIndex].SetVertices(vertList);
       tempCubeMeshArr[cubeIndex].SetTriangles(triangleList, 0);
       ...
}

How is the value at this index in the mesh array null when I set it to new Mesh()? I know the vertList is not null because I have printed it to the console, and even assigned it to a different mesh. I’d definitely appreciate any help after sinking hours into this issue.

When does function() get called? Is it possible it’s being called before Start()? Maybe in an Awake() or OnEnable() method somewhere?

Does tempCubeMeshArr get assigned anywhere else besides in Start()?

tempCubeMeshArr sure was being assigned elsewhere, I was assigning it to null in a loop I thought was being bypassed. It’s always the little things… thank you!

1 Like