I’m trying to make a array of a class but Unity throwing error when assigning values to arrays
Object reference not set to an instance of an object.
The Code:
public class StringClass {
public string name;
}
private void JsonParsing()
{
StringClass[] stringClass = new StringClass[3]; // am i not creating object for array in here?
stringClass[0].name = "test0"; // Error
stringClass[1].name = "test1";
stringClass[2].name = "test2";
stringClass[3].name = "test3";
The string array works perfectly fine but the class arrays just don’t work properly
>Solution :
Thanks to @UnholySheep for pointing that there’s two issues here.
Array sizes
StringClass[3] is just defining the size of the array to be 3. Which means you can use the array indexes 0-2. Sizes are always counted from 1, while indexes start at 0.
Initiating array elements
In the array you will need to initiate each element before setting its properties.
In your code you only set the size of the array and never initiated any elements in it. But you still tried changing the properties of a element, resulting in trying to access a null object.
Example:
class StringClass
{
public string name;
}
internal class Program
{
private void JsonParsing()
{
/*
Since this isn't a value type array,
we need to initiate each element before
modifying any properties of it.
*/
StringClass[] stringClass = new StringClass[2];
// initiates the element of the first index
stringClass[0] = new StringClass();
// now we can modify this!
stringClass[0].name = "test0";
// Do it again on the next index
stringClass[1] = new StringClass();
stringClass[1].name = "test1";
}
}