A Flash Developer Resource Site

Results 1 to 5 of 5

Thread: For loop and incrementing object names

  1. #1
    Senior Member
    Join Date
    Apr 2002
    Posts
    682

    For loop and incrementing object names

    I'm trying to loop through some objects, and I'm doing something wrong.

    I'd like to do the following to some sound channel objects.

    for (var n:Number = 0; n<5; n++) {
    _root["sc" + n].stop();
    }

    Obviously, I can't do that in AS3, but that's what I want to do. The _root path is not important. I only added it because that syntax used to work in AS2. How can I loop through incrementing object names?

    Thanks.

  2. #2
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    grr. lost my response. First point: don't group by naming convention if you can help it. Use Arrays instead.

    Second, you need to cast things to tell the compiler what type of object they really are, and you need to know the difference between properties and things on the displayList. If you're accessing displayList children by name, you're looking for the getChildByName method.

    If your SoundChannels are actually properties of your root:
    Code:
    for (var n:Number = 0; n<5; n++) {
    MovieClip(root)["sc" + n].stop();
    }
    Since SoundChannel is not a DisplayObject, getChildByName doesn't apply to your situation. Let us know if the above doesn't work, because it depends on some assumptions about your code.

  3. #3
    Senior Member
    Join Date
    Apr 2002
    Posts
    682
    Thanks. I'm not sure what you mean by grouping by arrays. I know how to use arrays, just not what you mean. Are you saying myArray[1] = false?

    How about simple Boolean variables. For example:

    var isPlaying1:Boolean = false;
    var isPlaying2:Boolean = false;

    Then, in a function some place:

    for (var n:Number = 0; n < 5; n++) {
    "isPlaying" + n = false;
    }

  4. #4
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    By "group by Arrays", I mean use an Array to contain all the instances of whatever it is you care about, and go through that rather than try to build instancenames. The code you posted won't work, because you're trying to assign a Boolean value to a String.

    Code:
    var isPlayingArray:Array = new Array();
    
    for (var i:int = 0; i < 5; i++){
      isPlayingArray[i] = false;
    }
    
    trace(isPlayingArray[4]); //traces "false"
    You could just as easily put the actual SoundChannels in the array instead.

  5. #5
    Senior Member
    Join Date
    Apr 2002
    Posts
    682
    Thanks. Enlightening and it worked great.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center