;

PDA

Click to See Complete Forum and Search --> : Access of undefined property instance1


regbolD
01-17-2009, 08:09 AM
if i create a new sprite/ or a movieclip and then add it to the stage:

var someName:Sprite = new Sprite();
addChild(someName);

that sprite/moviclip is going to have some instance name like "instance1"

i can see that with trace:
trace(someName.name);

but if i then say:
instance1.x = 100;

i wil get an error: "Access of undefined property instance1"

i know i can say:
someName.x = 100;

but why cant i get to it through its instance name, or can i somehow?
and what is the point of that instance name then?

the reason i am asking is if i have multiple sprites with the same name, but different instance names how could i get to each of them in that case?

jAQUAN
01-17-2009, 12:32 PM
It's not clear if you are talking about instances placed at authortime or runtime.
If you create a new display object and assign it to a variable, you can always manage it through that variable.

If you place an instance on the stage at author time and give it an instance name, by default Flash will create a variable by that name so that you can reference it through AS.

regbolD
01-17-2009, 12:38 PM
make a new as3 document and put this code in:

var someName:Sprite = new Sprite();
addChild(someName);
trace(someName.name); // output = instance1

and then try each of these 2 statements below:

// instance1.x = 100; // it doesnt work ("Access of undefined property instance1")

// someName.x = 100; // it works

so my question is why cant i change its properties through its instance name?

5TonsOfFlax
01-17-2009, 03:19 PM
Because things are not their names. An instancename is just a String property that is used by a few built-in functions. It is not a variable, and it is not magic.

There is no variable called instance1 in your code, which gives rise to the error.

You could use getChildByName("instance1"), but that would be quite inefficient since you already have a reference to the object in the someName variable.

regbolD
01-17-2009, 04:07 PM
thanks, I got an answer on another forum to use this in that case:
getChildByName("instance1").x = 100;

You could use getChildByName("instance1"), but that would be quite inefficient since you already have a reference to the object in the someName variable.

I dont agree because if I am generating new sprites in a loop like this:

for (var i=0; i<=5; i++) {
var someName:Sprite = new Sprite();
someName.x = 90*i;
addChild (someName);
}

then how would I reference them if they all have the same name?
then I would had to use instance name, wouldnt I ?

5TonsOfFlax
01-18-2009, 12:12 PM
In a situation like that, you should use a collection such as an Array or Vector.


var mySprites:Array = new Array();
for (var i = 0; i <= 5; i++){
var someName:Sprite = new Sprite();
mySprites.push(someName);
someName.x = 90*i;
addChild(someName);
}

//later

mySprites[3].y = 20;

regbolD
01-18-2009, 02:16 PM
interesting, thanks!