简体   繁体   中英

AS3 - Adding an object to a MovieClip Container from a class

I'm kind of new to adding using classes in AS3, so far i've just been doing everything on frame1 of the movie. I figured I should eventually learn classes so here goes :) When I add objects onto the screen, I like to group them together in container objects for use later. So I have a board of Hex's that I'm building, and I'm trying to get them into a MovieClip named hexContainer that I have places on the stage. Now if I was doing this code like I normally would, I would just do hexContainer.addChild(tempHex). However, this is throwing me an error 1120.

My class code is as follows:

package  
{
import flash.display.MovieClip
import Hex
import flash.display.Stage

public class Boards extends Hex
{
    public function buildBoardOne()
    {
        for(var i:int = 1; i <= 5; i++)
        {
            var tempHex:Hex = new Hex();
            tempHex.x = 100;
            tempHex.y = 100;
            hexContainer.addChild(tempHex);
        }
    }

}

}

I did in the beginning just have these added to the Stage and was getting an error when I did that, that's why the import statement is there. I had checked on google to figure out why and that's what they said to do.

Now, when I added these to the stage it worked fine. I could get my hex's and manipulate them and we partied and it was a great time. Now that I'm trying to put them into the container movie clip they are rather angry at me and I just can't appease them :p

Any help you guys could give me would be greatly appreciated.

Edited code to test out what okayGraphics suggested:

package  
{
    import flash.display.MovieClip
    import Hex
    import flash.display.Stage

    public class Boards extends Hex
    {
        var hexContainer:MovieClip = new MovieClip();
        stage.addChild(hexContainer);

        public function buildBoardOne()
        {
            for(var i:int = 1; i <= 5; i++)
            {
                var tempHex:Hex = new Hex();
                tempHex.x = 100;
                tempHex.y = 100;
                stage.addChild(tempHex);
            }
        }

    }

}

You are getting an 1120 error because hexContainer is not defined in this package. You either (1)need to declare var hexContainer = [your_reference_here] before you try to add children to it,

or

(2)you can just add the hexes as children to the Boards class, then add that to your hexContainer. instead of hexContainer.addChild(TempHex); just put addChild(TempHex);

There's lots of other ways to do it too, but I think these two are the most straightforward approaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM