0

UPDATED ANSWERED: Found a WORK AROUND. I changed my array to an array of mc names rather than strings so it works now. Nevertheless, curious if this question could be answered.


I have a random array of string names. I sort them out randomly. But I need to add an existing movieclip based the string name.

Here is what I have that doesn't work.

public function addToStage()
{
    Happy = sorted.sort( randomize );
    trace("First is: " +Happy[0]); /// Works! 
    addChild(Happy[0]); // Does not work
}

ERROR I GET TypeError: Error #1034: Type Coercion failed: cannot convert "Apple" to flash.display.DisplayObject. at Main/addToStage()[C:etc..\Main.as:74] at Main/init()[C: etc...\Main.as:64] at Main()[C: etc... \Main.as:25]

2
  • Are the strings class names, or instance names? Commented Jan 9, 2014 at 8:23
  • Yes. It seems to be working if I lose the quotes. Commented Jan 9, 2014 at 8:29

3 Answers 3

2

Assuming the strings in the array are names of MovieClip vars then it's as simple as this:

this.addChild(this[Happy[0]])

That effectively looks for a variable with the name equivalent to the string in the array, so this["hello"] will look for this.hello

If the strings aren't names of movieclip vars then you would need to "map" the movieclips to the strings using a dictionary or Object like so:

var dictionary:Dictionary = new Dictionary;
dictionary["hello"] = movieClipVariable;

this.addChild(dictionary["hello"]);

Let me know if this isn't what you meant and I'll have another look

Sign up to request clarification or add additional context in comments.

Comments

0

Arrays are dynamic, types are lost on children of the array, the are stored as Object. to add the to the display list you must cast them to a DisplayObject or class that extends a DisplayObject:

addChild(Happy[0] as DisplayObject); // should work

Comments

0

you have to do type cast a from object to displayobject.

private var tempMC:MovieClip;

public function addToStage()
{
    Happy = sorted.sort( randomize );
    trace("First is: " +Happy[0]); /// Works! 
    tempMC = Happy[0] as MovieClip;
    addChild(tempMC); // it should work
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.