Search code examples
flashactionscript-3arrayscastingflash-cs4

ActionScript 3 Array Casting problem in Flash CS4


I have these Arrays

   //Array elements are Sprites (Class) in Flash Library

    var elements:Array  = new Array (el1_spr, el2_spr, el3_spr);
    var container:Array = new Array();

    for var (i:uint; allElements.length; i++){
       container.push(allElements[i]);
       var v:Sprite = (allElements[i] as Sprite);

    addChild(container[i]);
    Puzzle.polozaj.(container[i]);

//Error is:
//TypeError: Error #1034: Type Coercion failed: cannot convert el1_spr$ to flash.display.DisplayObject.
    at project_fla::MainTimeline/frame1()




}

Solution

  • Looks like you could probably add v to the display list, rather than container[i]. Have you tried that?

    UPDATE: Actually, I think the problem comes from the second item in your loop definition. It should be i < allElements.length, rather than allElements.length. The way you've got it set up, it is running one time more than it should.

    Below is some working code, based on what you posted, above. Hit me with a comment if I need to clarify (anyone - been a rough morning, so far...).

    var el1_spr:Sprite = new Sprite;
    var el2_spr:Sprite = new Sprite;
    var el3_spr:Sprite = new Sprite;
    
    el1_spr.graphics.beginFill(0x0000FF);
    el1_spr.graphics.moveTo(0,0);
    el1_spr.graphics.lineTo(100,0);
    el1_spr.graphics.lineTo(100,100);
    el1_spr.graphics.lineTo(0,100);
    el1_spr.graphics.lineTo(0,0);
    el1_spr.graphics.endFill();
    
    el2_spr.graphics.beginFill(0x00FF00);
    el2_spr.graphics.moveTo(0,0);
    el2_spr.graphics.lineTo(100,0);
    el2_spr.graphics.lineTo(100,100);
    el2_spr.graphics.lineTo(0,100);
    el2_spr.graphics.lineTo(0,0);
    el2_spr.graphics.endFill();
    
    el3_spr.graphics.beginFill(0xFF0000);
    el3_spr.graphics.moveTo(0,0);
    el3_spr.graphics.lineTo(100,0);
    el3_spr.graphics.lineTo(100,100);
    el3_spr.graphics.lineTo(0,100);
    el3_spr.graphics.lineTo(0,0);
    el3_spr.graphics.endFill();
    
    var elements:Array  = new Array (el1_spr, el2_spr, el3_spr);
    var container:Array = new Array();
    
    for (var i:uint; i < elements.length; i++)
    {
        container.push(elements[i]);
        var v:Sprite = (elements[i] as Sprite);
    
        addChild(v);
        //addChild(elements[i]);        // this also works
        //addChild(container[i]);       // this also works
    
        v.x += (100 * i);
        //elements[i].x += (100 * i);   // this also works
        //container[i].x += (100 * i);  // this also works
    }
    

    I don't know what the context of your code is, but for what it might be worth, I included a couple of extra lines to show that you don't necessarily need the container Array, or to create v.

    Hope that's helpful.