简体   繁体   中英

Creating a vector array of movie clips AS3

I have several movie clips on the stage of my main .fla named btn1-btn7 which will act as buttons. I have a class file named Functions.as where an event listener is created when a button is clicked. onButtonClicked is just going to a frame on the timeline.

obj.addEventListener(MouseEvent.CLICK, onButtonClicked);

I would like the ability to set the buttonMode, visibility, etc. of all of the buttons simultaneously. I have been looking into this for a few hours and am not able to find any solutions. I am now looking into adding them to a vector (which is a new concept for me), but I am not sure how to go about executing this properly. This is what I have so far.

public var buttons:Vector.<MovieClip >  = new Vector.<MovieClip > ();


        function addButtons()
        {
            buttons.push(btn1,btn2,btn3,btn4,btn5,btn6,btn7);

            for (var i:int; i<buttons.length; i++)
            {
                trace(buttons[i].name);
            }


        }

How would I go about, for example, adding the event listener to all of the objects? I will also be setting the buttonMode to true, and making them all invisible simultaneously. I don't even know if it's possible to accomplish this. Thank you in advance for any suggestions.

You just need to do what you are doing with the .name property in your example code. You need to loop thru every single button in your array (or vector, if you prefer). Here is an example how to set the property of buttonMode:

function setButtonMode(b:Boolean):void {
    for(var i:int=0; i<buttons.length; i++) {
        var btn:MovieClip = buttons[i]; //store the current reference in a var for faster access
        btn.buttonMode = b;
        btn.mouseChildren = !b;
    }
}

I'm going to asume that you use timeline code, and have instances of the buttons already placed on the stage. So, first, create the vector:

var _btns:Vector.<MovieClip> = new Vector.<MovieClip>;
_btns.push(btn1,btn2,btn43....) //add all the buttons

Than, you can init the properties of all the buttons:

var _mc:MovieClip;//helper var
for(var i:int=0,i<_btns.length;i++)
{
   _mc = _btns[i];
   _mc.visible = false;
   _mc.buttonMode = true;
   _mc.addEventListener(MouseEvent.CLICK, onClick);
}

Then, the event handler:

function onClick(e:MouseEvent):void
{
  for(var i:int=0,i<_btns.length;i++)//reset all the buttons
  {
    _btns[i].visible = false;
  }

  _mc = MovieClip(e.eventTarget);
  _mc.visible = true; //make visible the clicked one
}

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