- Home /
How could I instantiate to a GameObject variable in a class?
class GaragesClass {
var unit : GameObject = new GameObject();
}
var unit : GameObject;
private var floors : int = 12; private var garages : GaragesClass[] = new GaragesClass[floors];
private var baseHeight : float = -2; private var height = 16.66666;
function Awake () {
for (var i : int = 0; i<floors; i++) {
garages[i].unit = Instantiate(unit, Vector3(0, baseHeight*height+i*height, 0), Quaternion.identity);
}
}
Instantiating gives the error "Object reference not set to an instance of an object"
Answer by Berenger · Dec 23, 2010 at 08:23 AM
You just forgot to instantiate your array elements. add this line
garages[i] = new GaragesClass();
at the beginning of the for loop, and it's gonna work.
Thank you, it worx! Is it because the assignment "new" doesn't work outside a function? Because at the beginning I already wrote
"private var garages : GaragesClass[] = new GaragesClass[floors];"
You do need that lines, it create a an array of empty objects (and specify the size by the way), but each ones inside need to be built too. So you need both.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092240im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Class hierarchy, gameObject, Raycast 1 Answer
transform in a custom class 2 Answers
Null reference exception after instantiating a light gameobject 0 Answers
Rigidbody: NullReferenceException: Object reference not set to an instance of an object 1 Answer
OnCollisionEnter GameObject throws NullReferenceException 0 Answers