A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: Can you put: _root.mc.onPress = function(){ inside a FOR { loop?

  1. #1
    Running Plodding & Limping SpockBert's Avatar
    Join Date
    Jun 2002
    Location
    London
    Posts
    593

    Can you put: _root.mc.onPress = function(){ inside a FOR { loop?

    Hi trying to do something really simple here but its not working properly. Using Flash 8.

    I have 3 movieclips (to be turned into buttons) on the main stage, instances named: "charm1", "charm2" and "charm3". On the main timeline, I have this code. Using a for loop I'm trying to assign a bit of code to each movieclip when its clicked on:
    Code:
    for (i = 1; i < 4; i++){
    
        trace ("i value:" + i);		
        // displays, "i value:1", "i value:2", "i value:3" like it should
    		
        _root["charm" + i].onPress = function(){
    
            trace ("i value:" + i);
            //displays "i value:4" for all 3 buttons, makes no sense!
    
        };
    
    }
    
    

    Why is my value for i, being incremented? Can anyone help, are there certain bits of code that aren't allowed inside a For loop?

    Cheers
    Si
    Last edited by SpockBert; 07-03-2009 at 11:51 AM. Reason: Missed out Flash version.

  2. #2
    FK'n_dog a_modified_dog's Avatar
    Join Date
    Apr 2003
    Location
    "aaarf"
    Posts
    9,176
    for(loops) only update after the last iteration, hence all output is the same
    so specify an individual variable to each movieclip -
    PHP Code:
    for (14i++){
        
    trace ("i value:" i);        
        
    // displays, "i value:1", "i value:2", "i value:3"
        
    _root["charm" i].iVar i;
        
    _root["charm" i].onPress = function(){
         
    trace ("i value:" this.iVar);
         
    //now displays "i value:correct" for all 3 buttons
        
    };


  3. #3
    Running Plodding & Limping SpockBert's Avatar
    Join Date
    Jun 2002
    Location
    London
    Posts
    593
    Thanks "dog"!

    I gotta be honest, I still don't understand why that original code messes around with i and comes up with "i=4" for all 3 clips, but ah well, your code works great, I've adapted it for my movie and it works now, thanks for that!

    You taught me something else, I never knew you could assign a variable to a movieclip like that. I thought the only vars attached to clips were the basics like ._x, _y, _visible etc etc, I didn't know you could do stuff like "_root.myClip.anythingIlike = 3;

    Thank you so much for your help, massively appreciated
    Last edited by SpockBert; 07-07-2009 at 06:31 AM. Reason: poor spelling

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