Hey there,
I forget how to setup dynamic arrays for class objects. I forget the syntax
.
I get “Object reference not setup to an instance of object”. I understand what this means, I have a reference to a data type, but no memory allocated to this pointer. I just forget the proper syntax to fix this.
class Actor
{
var name;
};
function Start()
{
var actors : Actor[];
actors = new Actor[5];
actors[0].name = "Joe";
Debug.Log(actors[0].name);
}
I get a syntax error for:
actors = new Actor[5];
Thoughts?
Alex
this is code that was posted on another similar thread - hope it helps
//javascript class
class TestContainer {
//inspector values
var myObject : Transform[];
var max_Velocity : float;
var max_Force : float;
var distance : float;
var rotationSpeed : float;
function TestContainer () {
max_Velocity = 3.0;
max_Force = 0.8;
distance = 0.1;
rotationSpeed = 3.0;
}
}
//inspector values
var totalObj = new TestContainer[10];
for (obj in totalObj) obj = new TestContainer();
oh I would forget to build a contructor lol
thank you very much
Alex
You don’t actually need a constructor. You do need to initialize any entry in the array you’re actually using though, whether it’s through a constructor or not.
var actors : Actor[];
actors = new Actor[5];
actors[0].name = "Joe";
should be
var actors = new Actor[5];
actors[0] = new Actor();
actors[0].name = "Joe";
With a constructor you could do
var actors = new Actor[5];
actors[0] = new Actor("Joe");
Also, your class should read:
class Actor
{
var name : String;
};
Note that this isn’t a dynamic array. For that you’d use Array rather than an array of Actor.
–Eric
I tried that earlier, it wasn’t happy with the third line. It still wasn’t referring actors[0] to an instance of Actor. Once I defined a blank constructor in my class and did that, it was happy.
As for
var name : String
Thanks! I’ve been trying to find the identifier for the data type String, but I never thought of using a capital S. I just left it blank and let unity assign it.
Cheers
Not sure what to say…that does work, and is how you initialize an instance of a class if it doesn’t have a constructor. I’d guess there was a typo somewhere.
–Eric