AS3 reference movieclip by .name property

18,933

Solution 1

you want to use getChildByName("name") more info

import flash.display.MovieClip;

// create boxes
for(var i:int = 0 ; i < 4; i++){

    var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox

    box.name = "box_" + i;
    box.x = i * 100;
    this.addChild(box);

}

// call one of the boxes

var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
targetBox.gotoAndStop(2);

Solution 2

Accessing things by name is very prone to errors. It's not a good habit to get into if you're a newbie. I think a safer way to do this would be to store references to the things you're creating in the loop, for example in an array, and reference them by their indexes.

Example:

var boxes:Array = [];
const NUM_BOXES:int = 4;
const SPACING:int = 100;

// create boxes
for(var i:int = 0 ; i < NUM_BOXES:; i++){

    var box:MovieClip = new MovieClip(); 

    // You can still do this, but only as a label, don't rely on it for finding the box later!
    box.name = "box_" + i; 
    box.x = i * SPACING;
    addChild(box);

    // store the box for lookup later.
    boxes.push(box); // or boxes[i] = box;
}

// talk to the third box
const RESET_FRAME:int = 2;
var targetBox:MovieClip = boxes[2] as MovieClip;
targetBox.gotoAndStop(RESET_FRAME);

Note, I've also replaced many of the loose numbers with constants and vars which will also help your compiler notice errors.

Solution 3

You can use the parent to get the child by name. If the parent is the stage:

var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);
Share:
18,933
FoxLift
Author by

FoxLift

Updated on June 04, 2022

Comments

  • FoxLift
    FoxLift almost 2 years

    Yay, another simple noobie as3 question.

    How can I reference a movieclip by its ".name" ?

    I tried searching for a solution, but I couldn't find anything. Basically I have a set of movieclips added to the stage using a loop, so the way I found to diferentiate them was by giving them a .name of "something" + the Loop's "i". So now they are named something like "something1", "something2", "something3", and so on.

    Now, I need to send some to a specific frame. Usually I would do something like:

    something1.gotoAndStop(2);
    

    But "something1" isnt the instance name, just the ".name". I cant find a way to reference it.

  • FoxLift
    FoxLift almost 12 years
    Whenever I use getChildByName("something1"); I get an "label must be a simple identifier" error.
  • Boyd
    Boyd almost 12 years
    ok I added the code above and tested it. Should work just fine.
  • FoxLift
    FoxLift almost 12 years
    Thanks for the helpful advice!