"Null Reference Error" when using a custom class as an array

Hey everyone!

I have been using a code that has a custom class in it and have come across a problem.

When this code is called at runtime:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class CustomClass {
	public Transform aTransform;
	public string aName;
}

[System.Serializable]
public class Test : MonoBehaviour {

	public CustomClass[] cClass;
	
	void Start () {
        cClass = new CustomClass[1];
        cClass[0].aName = "A new name";
	}
}

I get this null reference error:

NullReferenceException: Object reference not set to an instance of an object

I fairly sure the problem is when I change the value of cClass to be of length 1, but I do not know how to fix the problem.

Can anyone give me a hand? Cheers.

-AJ

You need to create an instance of the custom class as well as the array (it’s different with structs).

As well as the array creation you need:

  cClass[0] = new CustomClass();