Search code examples
arraysactionscript-3flashcastingmovieclip

Cast a stage child movieclip into a custom class extends movieclip AS3


I'm creating a program where I add multiple Movieclips to the stage in Flash, instance name them 'item_#' per frame, and at runtime I pull these children into an array and dynamically cast them to a custom class called 'Item' which extends MovieClip.

function loadUpItems(): Array //loads items into ItemArray{
var ItemArray:Array = new Array(); //Dynamically holds the items_# for each scene

for(var i:int = 0; i<numChildren; i++) //loop number of children on stage
{

    if(getChildAt(i).name.substr(0,4) == "item") //if child is an item
    {
        trace("Item Child is: " + getChildAt(i));
        var mc:Item = new Item();       
        mc = getChildAt(i) as Item;
        mc.setItemX(getChildAt(i).x);
        mc.setItemY(getChildAt(i).y);
        mc.setItemNumber(Number(getChildAt(i).name.substr(5)));
        ItemArray[getChildAt(i).name.substr(5)] = mc; //Add to Items:array as instance numbered
        ItemArray[getChildAt(i).name.substr(5)].stop();
        trace("Loaded Item : " + ItemArray[getChildAt(i).name.substr(5)].itemName() + " : Frame : " + CurrentFrame);
    }
}
trace("ItemArray : " + ItemArray);
return ItemArray;}

The problem being I can't seem to cast them properly as I get a null at the point:

mc = getChildAt(i) as Item;

It worked when I was just pulling the items as MoviClips and didn't need to cast them:

mc = getChildAt(i) as MovieClip;

Help welcome,

Cheers,

Dan


Solution

  • Thanks for the help,

    I didn't apply library linkage. The base class of all the items was still set to MovieClip.

    So I went to the items Properties...>Export for ActionScript.

    And just changed the base class to my 'Item' class.

    To easy.