- Home /
Array of custom class objects, possible?
Hi, Say I have a custom class "person" and I want to make an array of objects of type person. How do I do that?
class Person{
var Age : int;
var Weight : float;
}
I want to know if it's possible to have an array of type person and access the components like "ClassB_Students[index].Age"
Answer by Mattivc · Jun 26, 2012 at 12:23 PM
You can define a array of "Person" objects like this
var personArray : Person[];
Or as the slower but more flexible array class
var personArray = new Array();
Read more about both types here.
Guess i read your question a bit fast. The answer is in UnityScript now.
Well, this is kind of what I was doing.. Later on the code I recreate the array to set a size "personArray = new Person[10];" Does this make sense? It works for other types, but for "Person" it gives "Object reference not set to an instance of an object" when I try to access some element of the array.
You need to instantiate a Person object for each element of the newly-declared array. The easiest way to do this would be in a for
loop that iterates through the array, calling personArray[i] = new Person();
Classes are no problem, it's only that the JS Array class is inferior to List and probably should be deprecated at this point, since List does everything Array does faster and better, and doesn't cause issues when using #pragma strict. (Also note that the JS Array class is not the same as built-in arrays such as Person[], which are fine.)
Your answer
Follow this Question
Related Questions
Does anyone know of good tutorials for learning arrays and classes? 1 Answer
Inventory Help. 2 Answers
Organizing variables in the inspector 5 Answers
JesseEtzler's RPG Talent System in C# 1 Answer
Basic Stuff on Arrays 1 Answer