3 Replies Latest reply on Jun 28, 2011 3:11 PM by Ned Murphy

    Arrays: using for loop and onPress

    prodigalmaster Level 2

      Im not very good with arrays. Here is my broken code:

       

      //Create array with 4 movieclips
      var invArray:Array = new Array("i_greenLine", "i_orangeDot", "i_yellowBlock", "i_brownThing");
      //repeat this code for every item (+1)
      for (i=0; i<invArray.length; i++) {
           trace(invArray[i]);
           //Outputs:
           //i_greenLine
           //i_orangeDot
           //i_yellowBlock
           //i_brownThing
           invArray[i].onPress = function() {
                trace("hit");
           };//the movieclips are not clickable.
      }
      

       

      Is there a way to get the movieclips on the stage to be clickable via an array? There will be lots and lots of movieclips.

      help?

      thanks?

        • 1. Re: Arrays: using for loop and onPress
          Ned Murphy Adobe Community Professional & MVP

          If you use Strings of the instance names for the array, then you will need to use bracket notation to target the instances with them...

          var invArray:Array = new Array("i_greenLine", "i_orangeDot", "i_yellowBlock", "i_brownThing"); for (i=0; i<invArray.length; i++) {      this[invArray[i]].onPress = function() {           trace("hit");      }

          }


          An alternative would be to just use the instance names and not Strings of them....

          var invArray:Array = new Array(i_greenLine, i_orangeDot, i_yellowBlock, i_brownThing);

          for (i=0; i<invArray.length; i++) {      invArray[i].onPress = function() {           trace("hit");      };

          }

           

          If you plan to have alot of them, then a better approach would be to name them all with numeric ending (mc0, mc1, mc2, mc3, etc.  Then you could use the bracket notation without the need for the array...

          for (i=0; i<numMCs; i++) {      this["mc"+i].onPress = function() {           trace("hit");      }

          }

          • 2. Re: Arrays: using for loop and onPress
            prodigalmaster Level 2

            I would love to use the last example, however all of the mcs will have different names so they are identifiable. However the second example works just fine, thanks!