Search code examples
actionscript-3movieclipaddchild

AS3 - Acccessing MovieClip after moving it to container


On the stage i have two MovieClips named 'mc1' and 'container'.

When i put 'mc1' inside the 'container' using addChild(), i expect to access it by its new parent - container.mc1

However, such attempt generates an error.

Weirdly, i can still access it normally, as if it still was on the stage, not inside the container.

trace(mc1.name); // outputs 'mc1'
container.addChild(mc1); // moves mc1 into container
trace(mc1.name); // outputs 'mc1' (why, it's not there anymore???)
trace(container.mc1.name); // TypeError:
Error #1010: A term is undefined and has no properties.

Can someone explain this to me? I am sure the mc1 is inside the container, so why i can still only access it as if it was on stage?

What if i had two MCs with the same name - one on the stage and one inside the container, how could i access them separately?

Big thanks!


Solution

  • Yes, container.addChild(mc1) adds mc1 to container.

    Now you expect to access mc1 via the dot operator. Please remember that the dot operator is used to access members of an object: properties and methods. (or variables and functions or however you want to call them)

    I am sure the mc1 is inside the container, so why i can still only access it as if it was on stage?

    The dot operator has no relationship to the display list whatsoever. Accessing just mc1 has no implications on what container mc1 was added to.

    Calling addChild() on container does not add a property to container that has the same name as the child you are adding. That's why you get the error.


    You are confusing two things here: the object and the reference to that object (that is, the variable)

    mc1 references an object. Passing that object to addChild() does not "move" the reference (mc1) anywhere. mc1 stays where it was defined.


    And here comes the reason why you are confused.

    Adobe Flash has a setting that automatically adds names of children as properties to containers. If you place mc1 in container "by hand" in Adobe Flash, you will be able to access container.mc1 because the Flash IDE adds this property behind the scenes, but if you add it via container.addChild(mc1) it will not have the property.

    What if i had two MCs with the same name - one on the stage and one inside the container, how could i access them separately?

    If you placed the on in the container by hand, the property would be automatically created and thus container.mc1 and mc1 would be different objects.

    If you add them via code, you have to give them different names, because the whole point of the names is to identify objects, which is why they should be unique. If you have many mcs of the same kind, you should use an array and not individual variables with numbers at the end (mc1, mc2,...)