- Home /
"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
Answer by whydoidoit · Jun 02, 2012 at 08:52 AM
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();
Thank you very much!
Is there any way to avoid having to do this?
Thanks again,
-AJ
No, that's a basic aspect of how classes work; they are null unless initialized. I'd suggest adding a constructor though.
Cool, good to know. Will be doing!
Thanks for your help!
-AJ
The only way to avoid doing it, is to teleport to the year 3755AD, where computers don't have memory, but work with neo-quantum disentangled reversible hyperstates. But don't tell anyone I told you that.
At first is was like:
Ohh! That could be cool!
But then I was like
Ohh! That would be freaking amazing!
GIIIIIIII$$anonymous$$$$anonymous$$$$anonymous$$$$anonymous$$$$anonymous$$$$anonymous$$$$anonymous$$IIIIIIEEEEEE!
Your answer
Follow this Question
Related Questions
transform in a custom class 2 Answers
Pushing GameObject into JS Array returns NullReferenceException 1 Answer
Instantiating gameobjects in an array / class problem | NullReferenceException: 0 Answers
Problem with Singleton and NullReferenceException? 0 Answers
Custom Class Array Serialization Problem 0 Answers