views:

116

answers:

2

I am creating a bunch of objects in an array. I'm used to doing this iteratively, like

for(i:int; i < number; i++){
  ball= new Ball;
  balls.push(ball);
  }

and then later I can make reference to balls[i]. Now however I'm creating the objects with mouse click, not with a for loop, so I don't have that [i], so my other code makes reference to just "ball", which means it affects only whichever one was just created. Is there any reasonable way to 'name' each object arbitrarily so I can later say "each of you go off and do your own thing, and ignore everyone else"?

A: 

There is a couple of solutions,

If you have a reference to the ball, you can use

myArray.indexOf(myBall)

Which will give you its position in the array, so you can talk to it.

you can also store them with a name value like this:

myArray["name" + uniqueIdentifier] = myBall;

That would replace your push statements.

Alternatively you could just loop over them all like this:

for(var i:int = 0; i < myArray.length; i++)
{
    ball = myArray[i];
    //perhaps you stored a value on ball to distinguish when it was created
    if(ball.wasCreatedByMouseClick) // do something
}

Hope that gives you some ideas.

Tyler Egeto
This is pretty much precisely what I had in mind. Thank you!
A: 

i don't know what your code is doing but according to what you described i'd use a dictionary to store your objects with a string key.

dictionary class behaves as an object in which you can set a dynamic property (key) and its value (your object). it's different from a object because keys could be anything (strings, objects, arrays,...anything).

this is an example:

var d:Dictionary = new Dictionary (true); d["myBall"] = new Ball();

function getBallByKey(key:String):Ball { return d[key]; }

depending on the scenario a good thing is to set dictionary references to weak. this is to avoid memory leaks (actually letting the object "die" as no other reference but the dictionary itself is pointing at that object)

Piergiorgio Niero

pigiuz
Hi Pigiuz, There is a common misconception with dictionaries and weak keys. As you mention, the keys are weak, but no the value. If you store a Ball object in a dictionary as the value, as in your example, it will never be auto-cleanup. Weak keys only apply when you use an Object as the key.
Tyler Egeto
sorry, i knew that behaviour and i didn't mention that...my fault :)however, good practice is to always delete the key when removing an object.
pigiuz
Yes, I definitely agree, always better to clean up after yourself.
Tyler Egeto