I have the following problem:
I have an array of unique instances of one Prefab, now I want to get 2 variables attached to each instance (it’s anchor and a distance variable).
Here’s how I create the array:
var rubberBand:GameObject;
private var uniqueRubberBand:GameObject;
private var lastRubberPos:Vector3;
private var rubberBandName:String;
static var rubberBandNameArray = new Array ();
uniqueRubberBand = Instantiate(rubberBand, linepos, transform.rotation);
rubberBandName = "RubberBand";
rubberBandName = rubberBandName.Insert(rubberBandName.Length, rubberBandNameArray.length.ToString());
uniqueRubberBand.name = rubberBandName;
rubberBandNameArray.Add(uniqueRubberBand.name);
And here’s how I access it from another script:
private var rubberBand:GameObject;
private var rubberBandScript:Component;
for(i = 0; i < DrawPathFullTrackScript.rubberBandNameArray.length; i++)
rubberBand = GameObject.Find(DrawPathFullTrackScript.rubberBandNameArray*);*
rubberBandScript = rubberBand.GetComponent(RubberbandScript); anchor = rubberBandScript.anchor; distance = rubberBandScript.distance; My problem is that I only get the anchor and the distance of the last created instance, even though every instance is uniquely named :-/
In the code you’ve posted, only the first instruction after the for is executed inside the loop - the others will be executed after the loop has ended, thus only the last object
is modified.
You should enclose the loop instructions inside brackets:
Anyway, there’s a much better way to do this: tag the clones as “RubberBand” (remember to register this tag!), get all of them in a GameObject array with GameObject.FindObjectsWithTag, then loop through the items with for:
var rubberBand:GameObject; private var uniqueRubberBand:GameObject; private var lastRubberPos:Vector3; static var rubberBandNameArray = new Array (); uniqueRubberBand = Instantiate(rubberBand, linepos, transform.rotation); uniqueRubberBand.tag = “RubberBand”; // set the clone tag as RubberBand // it’s easier to create the unique name this way: uniqueRubberBand.name = “RubberBand” + rubberBandNameArray.length.ToString(); rubberBandNameArray.Add(uniqueRubberBand.name); // When you need to set all RubberBand objects: private var rubberBand:GameObject; private var rubberBandScript:RubberbandScript; // declare the correct type! // get all RubberBand objects in an array: var rubberBands: GameObject[] = GameObject.FindGameObjectsWithTag(“RubberBand”); // loop through the array for(rubberBand in rubberBands){ rubberBandScript = rubberBand.GetComponent(RubberbandScript); anchor = rubberBandScript.anchor; distance = rubberBandScript.distance; … }