- Home /
Cannot access class array in dynamically created object
Using .js:
In a random script I create a dynamic object (empty GameObject):
var object = new GameObject("Hi");
Attach a component
object.AddComponent("Blah");
Blah.js looks as follows:
class Whatever {
var name : String;
}
var Nifty : Whatever[] = new Whatever[15];
function DoSomething(){
this.Nifty[0].name = "Sparky";
}
function Start(){
this.DoSomething();
}
This causes:
NullReferenceException: Object reference not set to an instance of an object
The error is occurring when I try and access this.Nifty[0]; I can't change or access any of the variables
Now I change it:
function Update(){
this.DoSomething();
}
The same error occurs. But now, if I click on the dynamically created object ("Hi") in the Hierarchy, the error stops in the Console AND this.Nifty[0].name is changed to Sparky. So, there isn't really an error in syntax here.
This bug did not occur when I used non-dynamically created GameObject and simply attached the script to a empty object already in the scene.
What is going on here?
Thank you.
Answer by whydoidoit · Jun 24, 2013 at 04:50 AM
Attaching a component by script does not set any of the "default" parameters that you see on the script when it is selected in the Inspector (I mean when the script is selected in the project, not an instance selected in the hierarchy). This is why most people just leave those blank and programmatically set them. Adding a component in the editor does set these values.
Answer by irdc · Jun 24, 2013 at 04:59 AM
Well, get to answer my own question after someone on the forum responded. Hooray!
Basically, when attaching the script to a non-dynamic object, it is possible to just use the following:
var Nifty : Whatever[] = new Whatever[15];
or
var Nifty = new Whatever[11];
This was causing some problems with dynamic objects. With dynamic objects, I had to use the following:
function Start () {
for(var i=0;i<11;i++) {
this.Nifty [i] = new Whatever();
}
this.DoSomething();
}
That worked!
Your answer
Follow this Question
Related Questions
How to preserve array of custom objects in inspector? 0 Answers
Add instantiate object to GameObject[] 2 Answers
What are GameTiles? 1 Answer
Unity Object Array C# 2 Answers
Swapping elements of an array 1 Answer