Cast DisplayObject to MovieClip

I am converting a Flash application to OpenFL.

One problem I now came across is that I need to cast a DisplayObject to MovieClip. I looked if it would have been possible to only use DisplayObjects, but then I would lose functionalities such as buttonMode, gotoandstop, etc, that belongs to the MovieClip. I can also not start from a MovieClip since I am doing "DisplayObjectContainer.getChildAt(i); which returns a DisplayObject.

I have tried both safe and unsafe casts, but both gives me the error: “Type Coercion failed: cannot convert flash.display::Shape@ef91b871 to flash.display.MovieClip”

Is there any work around for this? Or maybe someone has a tip on how I could solve this otherwise, cause I do not really know at the moment.

Thank you in advance!

You cant convert a Shape to MovieClip because shape is not a successor of a movie clip in the inheritance tree…
This is also not possible in AS3 and would result in a null or compile time exception.

If you could give a code snippet than i can suggest a solution.

This is where it goes wrong (this is the flash version):

protected function createButtons(movieclips:Vector.<DisplayObject>):Vector.<Button> {
    var converted:Vector.<Button> = new <Button>[];

    for each (var tMC:MovieClip in movieclips) {

        ----> Problem in OpenFL <-----
        converted.push(createComponent(tMC, Button));
    }

    return converted;
} 

private function createComponent(input:MovieClip, componentType:Class) : Component {
    var component:Component = new componentType(input);
    component.parentName = absoluteName;

    return component;
}

So I have a Vector with all the buttons from the asset, and I need to convert them into my Button class (which inherits from MovieClip. I hope it is clear.

Try casting in haxe:

converted.push(createComponent(  /*HERE IS THE FIX*/  cast(tMC, MovieClip)      , Button));

Notice that if tMC is not a MovieClip instance, this will result in a null.

To be on the safe side I also put in a check:

        if(Std.is(tMC, MovieClip)) {
            converted.push(createComponent(cast(tMC, MovieClip), Button));
        }

And it seems to be working! Thanks a lot for your help!

1 Like