- Home /
C#: Arrays inside Arrays create a NullReferenceExeption?
Hello. I am currently trying to create a Minecarft-esc game in Unity, but I've run into this Problem: The compiler tells me, it ran into a NullReferenceExeption, when trying to aceess an Array that is stored within a class, of which I've created an Array. Let the code do the talking:
public class Chunk{
public int[ , , ] New_Chunk = new int[10, 3, 10];
}
[...]
public Chunk[ , , ] Created_Chunks = new Chunk[300, 300, 300];
[...]
Created_Chunks[x,y,z].New_Chunk[x1,y1,z1] = 2;
=> NullReferenceException: Object reference not set to an instance of an object
World_Creator.Start () (at Assets/World_Creator.cs:37)
Why is this happening? Ive tried it with making one instance of Chunk, without an array, which worked. Why is this happening? I need some Help :(
The error is almost clear: go to World_Creator.cs at line 37 you're trying to access the property of an object that is null (it's not still initialized). If you don't post the code of the function World_Creator.Start, as it is also clearly mentioned in the exception, we cannot be helpful.
Like @SkaredCreations said, this line:
public Chunk[ , , ] Created_Chunks = new Chunk[300, 300, 300];
just creates a ~100$$anonymous$$B large array with 27 million references which are all "null" since you did never create a single Chunk instance.
Each Chunk instance (if they are actually created with new Chunk()
) would require, ignoring all overhead, at least 1200 bytes. So if you plan to initialize all elements in your Created_Chunks array you would require 27$$anonymous$$ * 1.2$$anonymous$$b == 32GB of memory. This is just ridiculous. You usually never need that many chunks at the same time. It's more common to use a dictionary to add / remove chunks on the fly.
Answer by Kartik1607 · Dec 19, 2014 at 04:26 AM
Hello, you need to instantiate each object of class Chunk in order to access the members. Like Bunny pointed,
public Chunk[ , , ] Created_Chunks = new Chunk[300, 300, 300];
is merely creating some reference which are null. You need to create one Chunk instance for each of these reference. To do so
for(int i = 0 ;i< 300; ++i)
for(int j=0;j<300;++j)
for(int k=0;k<300;++k)
Created_Chunks[i,j,k] = new Chunk();
Of course, this code should not be used and you need to implement Lists or Dictionary.
Learn about those here : Scripting Tutorial
Your answer
Follow this Question
Related Questions
[Solved] Actually totally explainable NRE with 2D array 0 Answers
Null reference when accessing GameObject in the Array(C#) 1 Answer
MergeSort function acting strange 0 Answers
NullReference when accessing GameObject in array (C#) 1 Answer
Editor forgets elements of array after saving changes to code 0 Answers