Maybe its very noob question, or I dont know how to ask, please forgive my mistake;
In my “script1” there are list of resources. they are declared as
public static float[] resources;
In my “script2” there is a line like this;
for (int i = 0; i < lbl_resources.Length; i++)
{
lbl_resources_.text = Script1.resources*.ToString();*_
} I need to know spesific resources in the game, not resource[ ], because I will access them later. like resource1=100, resource2=200 As far as I know; I thought It should be like this; void Awake() { resource[1]=100; resource[2]=50; (…) } It doesnt give any error after I’ve edit on this script, but they will give both error on play mode; NullReferenceException: Object reference not set to an instance of an object Script1.Awake () and "NullReferenceException: Object reference not set to an instance of an object Script2.Update ()" Where is my wrong? Can you help me? Thank you very much for your patience.
You just “declared” an array variable, but you never create an actual array. Arrays have a fix size which has to be specified when they are created.
So if you want to store 5 float values in that array do this:
void Awake()
{
resource = new float[5]; // create a new float array with 5 elements
resource[0] = 100f;
resource[1] = 50f;
resource[2] = 25f;
resource[3] = 12.5f;
resource[4] = 6.25f;
// The next line would cause an index out of bounds error since we only have 5 elements ( 0 - 4 )
// resource[5] = 1f;
}
You used a static array, Static variables are shared between all instances of that class. So you usually want to initialize it directly like this:
public static float[] resources = new float[] {100f, 50f, 25f, 12.5f, 6.25f };
Here we create the array in the field initializer. As you can see when you provide the values like this you don’t need to specify the element count. The compiler does this automatically. Since we have 5 values in there the array will automatically be of size 5.
Static variables can’t be serialized by Unity since they don’t belong to a concrete instance. If you declare an array like this in a MonoBehaviour class:
public float[] resources;
you usually don’t initialize the values manually. The Inspector of the editor will automatically create an instance (initially with 0 elements) and serialize those values. That allows you to edit the array in the Inspector.
This is not actually a list it is an array. Lists can be used by including using Systems.Collections.Generic at the top of a script and are declared as List<string> strings = new List<string>() which would make a new list of strings.
Your question refers to arrays. The reason you get this error is because in the first script you fill the 2nd and 3rd elements of the array but not the first (Remember computers start counting from 0 not 1) and in your second script you start the loop from 0 and the array does not have a value at array position 0 so it is just a null value.