When creating a class array its members are still not instantiated

Viewed 42

Sorry for the stupid question!

Why do I get a NullReferenceException: Object reference not set to an instance of an object?

public class myTestClass
{
    public string testString;
}

public class Test : MonoBehaviour
{
    public myTestClass[] testedClassObject;

    private void Start()
    {
        testedClassObject = new myTestClass[2];
        testedClassObject[0].testString = "test";  // --> Error
    }
}

I guess I need a constructor for the string in my class, but how should that look like?

1 Answers

When you create an array, the contents are wiped to zero, which for references means: all the references are null (creating an array or references does not also create objects for each element in the array). As such, you need to explicitly create objects for the contents. For example:

testedClassObject = new myTestClass[2];
testedClassObject[0] = new myTestClass { testString = "test" };

or perhaps more conveniently:

testedClassObject = new [] {
    new myTestClass { testString = "test" },
    // etc  
};

which performs the array and contents initialization at the same time (and infers the length for you).

Related