- Home /
Creating an array of custom objects
Hi all,
I have created a custom class of my own in javascript with attributes as shown below:
class ConceptNode{ //node to store concept/relation
static var concept = ""; static var activity = -1; static var activated = false; static var hyperConceptOf = new Array(); static var elementConcept = new Array();
function ConceptNode(con,act,hyper,ele){//constructor this.concept = con; this.activity = act;
hyperConceptOf.push(hyper); elementConcept.push(ele);
}
}
I then try to create an array of objects of the above class in another script which is attached to a GameObject using the following:
static var conceptList = new Array(); static var conceptNodeList = new Array();
function Update(){
}
function Start(){
conceptNodeList[0] = new ConceptNode("Landmark",0,"","Building");
conceptNodeList[1] = new ConceptNode("Building",0,"Landmark","Commercial");
for(var i=0;i<conceptNodeList.length;i++){
Debug.Log(conceptNodeList[i].concept);
Debug.Log(conceptNodeList[i].hyperConceptOf[0]);
}
}
It seems that both the ConceptNode objects which I've created in the conceptNodeList are the same object. The log messages show the same attributes for both iterations. is this due to javascript array passing by reference? Or am I doing something wrongly? Any help by anyone would be greatly appreciated.
Thank you
Answer by Stelimar · Dec 24, 2009 at 05:48 AM
Your variables shouldn't be static. static variables are the same for every instance of a class, which is why you're getting the same values no matter which instance you access. Just change this:
static var concept = "";
static var activity = -1;
static var activated = false;
static var hyperConceptOf = new Array();
static var elementConcept = new Array();
To this:
var concept = "";
var activity = -1;
var activated = false;
var hyperConceptOf = new Array();
var elementConcept = new Array();
Unless of course you actually need any of those variables to be static.
Thank you so much for your prompt and accurate answer Stelimar. That solved my problem. Cheers to you!
So sad when new users reciprocate by saying "that solved my question" and don't realize there's an "Accepted" button right there. :( By the way, this solved my question too! :)
Your answer
Follow this Question
Related Questions
Accessing a private var from a subclass 2 Answers
Asset swopping script help (customization) 2 Answers
Ship customization 1 Answer
Character Customization - Bone Parenting Error? 0 Answers
Best practice for character customization(unity3d free)? 1 Answer