2

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?

  • You instantiate only the array, and you need to instantiate also the object itself. testedClassObject = new myTestClass[2]; testedClassObject[0] = new myTestClass(); – user3026017 Oct 26 '20 at 15:31
  • Basically `testedClassObject[0]` has not been set. – Johnathan Barclay Oct 26 '20 at 15:33
  • As a tip: public fields are rarely a good idea, and it is usually a good idea to follow .NET naming conventions; I would expect, therefore, `public class MyTestClass`, `public string TestString {get;set;}` and `public MyTestClass[] TestedClassObject {get;set;}` (or perhaps even: `public List TestedClassObject {get;} = new List();`. None of these things impact the answer, so I'm just offering this as a side commentary. – Marc Gravell Oct 26 '20 at 15:34

1 Answers1

1

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).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900