Search code examples
actionscript-3flashclassmovieclip

How can I add instance names to movieclips using AS3


I have a FLA document with a movie clip called "mc_walls". This movie clip is in the stage over 50 times in the movie and I haven't assigned an instance name each movie clip.

I was wondering if there was a way to add the instance names using some actionscript?

I want all the "mc_walls" to have the name "wall".

I tried this code:

mc_wall.name = "wall";

But it returns with this error: 1119: Access of possibly undefined property name through a reference with static type Class.

Help will be great :)

Many Thanks,

Peter


Solution

  • My guess is that there is no instance on the stage with the instance name mc_wall, which is why you are getting the undefined property error. If there is not an instance name, then you cannot access it via an instance name, right ?

    Next problem you will have though is that you CANNOT modify the name of a Timeline DisplayObject via code. So you will get this error even if you did name it something and then try to change it from that instance name :

    The name property of a Timeline-placed object cannot be modified.

    My thought is that you likely need to learn about arrays and not use the name property as the way you manage collections of MovieClips such as your walls.

    For instance, if I did have them on the timeline I'd put them inside another MovieClip , basically using it as a container for all my walls and name that instance "wall_container". Then in code I'd do this :

    var walls:Array = new Array;
    for (var index:int = 0;index < wall_container.numChildren;index++)
    {
        var wall:MovieClip = wall_container.getChildAt(index) as MovieClip;
        walls.push(wall);
    }
    

    Now, if I wanted to access an individual wall, I can just go :

    var wall:MovieClip = walls[5] as MovieClip;
    

    or loop through all the walls to collision check or something I can go :

    for (var index:int= 0;index < walls.length;index++)
    {
       var wall:MovieClip = walls[index] as MovieClip;
       wall.x = 500;
       wall.y = 200;
       // do whatever you want to do with that wall
    
       //check collision ?
       if (player.hitTestObject(wall))
       {
           // handle collision with the wall
       }
    }