Search code examples
actionscript-3instantiationmovieclipobjectname

AS3 MovieClip name ambiguity


Summary: I create instances of various MovieClips via AS3, using MovieClip class objects that are defined in the library.

As each MC is instantiated, I push it into an array for later reference.

Finally I create an XML file that contains data related to each MC, including its name. This is the problematic part – the name has to be able to identify the respective MC when the XML is read back in. I don’t want “instance17” etc, which I assume will be meaningless in another session.

Background: I am not a career OO programmer and this is a temporary assignment, forming only a very small part of my long-term interests. It will probably be a couple of years before my next Flash project.

Create instance

Library object Type: MovieClip, linkage _brakepipe

Instantiation

var brakepipe: _brakepipe = new _brakepipe();
shapes.push(brakepipe);

Then later

var clip: MovieClip = shapes(i);
Trace (clip);

This yields

[object _breakpipe]

So it is giving me the class name, not the MC instance name. What property or method of MC would yield “breakpipe”? (Or even "_breakpipe" - without the "object" prefix?)


Solution

  • You can use an associative array. It could look like this:

    var shapes:Array = new Array();
    

    and then

    shapes.push({item:_brakepipe,_name:"brakepipe"};
    

    Essentially the curly brackets create an Object instance and the name before the colon (:) is the name you create that you want associated with the value after the colon.

    so now you can do this in a loop

    trace(shapes[i]._name+"\n"+shapes[i].item);
    // output: 
    // brakepipe
    // [object _brakepipe]
    

    The nice thing about this method is you can extend it for any number of properties you want to associate with your array element, like this:

    shapes.push({item:_brakepipe,_name:"brakepipe",urlLink:"http://www.sierra.com",_status:"used",_flagged:"false"};
    

    and now

    shapes[i]._status
    

    would return the string "used". And you could change that value at runtime to "new" by doing

    shapes[i]._status = "new";