0
votes

NINJA EDIT: For some reason, the same code works now, without any problem at all. I don't know what happened, or why, but I no longer have this problem

Here's the original post:


To put simply, I created a MovieClip, put it with addChild() to stage, and when I tried to call this piece of code:

MovieClip(root).someFunction();

It throws Error #1034: Type Coercion failed: cannot convert flash.display::Stage@4034f71 to flash.display.MovieClip.

I really can't figure out why this piece of code won't work. The object itself works perfectly, as I can call functions within it (that line of code is actually within a function). It's just that piece of code that is problematic

Can someone tell me where I went wrong?

EDIT: To better illustrate the situation, here's my pieces of code:

in a MovieClip, I have this function:

function bombReset():void
{
    bBombIsDropped = false;
    tCarpetBombTween.gotoAndStop(0);
    this.visible = false;
    MovieClip(root).carpetBombAttack(iPosition);
}

And on Scene1(root, the outermost parent) I have this function:

function carpetBombAttack(position:int):void
{
    damagePlant(15,vTileOccupant[(position-1)]);
}

If I create a MovieClip instance via addChild and call bombReset in it, Flash will throw an error

If I manually drag the MovieClip onto stage, when I call bombReset, it will work fine

2

2 Answers

0
votes

Your error means that the compiler doesn't know how a MovieClip and a Stage can be the same thing. Also, I'm not certain, but I believe the compiler will whine about someFunction not existing on the stage even if you casted the stage (aka root) correctly.

The proper way to solve this is by assigning a document class to your project and make someFunction a public method (class function).

The lay-mans solution (which I sometimes use when I'm being lazy) is the following

Object(this.stage).someFunction();

That works because you are type-casting this.stage in a way that makes the compiler think it's an Object instead of a Stage. Objects can have any number of undocumented properties and functions, thus allowing you to call items on the Object whether they are part of a class definition or not (and even ones that don't exist - which is where you can get yourself into trouble).

0
votes

The inheritance for Stage is Stage -> DisplayObjectContainer -> InteractiveObject -> ... while MovieClip is MovieClip -> Sprite -> DisplayObjectContainer -> InteractiveObject -> ... (I'd link directly to the docs but the pages keep crashing on me).

While they share common base classes, the Stage and MovieClip classes aren't actually related, so trying to cast one as the other will fail.

As you're doing the MovieClip(root) type cast and not the root as MovieClip cast, that's why you're getting the error you're getting.

Either cast it directly to the object that has the someFunction() defined, use the solution defined by Jackson, or if you absolutely know it's there, you can also do root["someFunction"]()