PDA

View Full Version : Casting Issue (I think)



dr_tchock
June 18th, 2009, 11:30 AM
Simple question, I hope.

I have some MovieClips on the stage which I want to loop through and convert them into a custom (Dragger) class (if their name starts with "drag_");

I usually pass each one as a parameter to the constructor of the Dragger class and then add them as a Child but I'm convinced there is a better way.

Can't I just cast them as Dragger?

this is what I've tried to do, but it doesn't work



private function initDraggers():void
{
var activity = activitiesArr[currActivity]; // gets current activity from array

draggersArr = []; // creates array
var len: int = activity.numChildren; // int for loop iteration

for (var i:int= 0; i < len; i++)
{
if (activity.getChildAt(i).name.indexOf("drag_") >= 0) // if MovieClip is intended to be a Dragger
{
var dragger: Dragger = activity.getChildAt(i) as Dragger;
}
}
}


this doesn't work

Krilnon
June 18th, 2009, 07:18 PM
Casting doesn't change the type of an object. You can't ever change the type of an object at runtime, actually. You generally just end up creating new ones.

Note/disclaimer: Depending on how you want to define 'cast', technically you could say that some of the primitive type conversion functions 'cast' an object, but I'm not using the term in that sense.

Since you have these clips onstage, they'll be instantiated automatically before you get to run your code.

It can be rather challenging to deal with certain combinations of stage items and dynamic code or content. Yours seems to be one of those cases. I can think of two ways to resolve your situation, but they both require that you 'take sides' on either the authoring tool side or the scripting side.

The authoring tool way would be to associate all of your MovieClips with the Dragger class by adjusting their linkage properties in the Properties inspector.

The way to script something similar would require that you remove the objects from the stage. You could do that before you publish the file or you could do it through code. Either way, you'd want to dynamically generate your Dragger instances and position them where they were in the authoring tool.

There are a couple other ways to do something similar, but really, there are too many ways to do it to list them all.

dr_tchock
June 19th, 2009, 04:22 AM
Thanks for your answer. I didn't realise you could set their class type in Linkage and have done that.