Marcolac
Marcolac

Reputation: 931

Change a variable on click actionscript

I would like to know how I could change a variable on click using actionscript.

I have :

     private var test:int   = 0;

     public function thisIsTest():void{
         test = test + 1;
        }

     <mx:Image left="10" bottom="10" source="@Embed(source='Assets/blabla.png')" click="thisIsTest()" buttonMode="true"/>

I would like to add 1 to the variable test each time I click on the button 'blabla'.

The problem is that it only works once.

Thank you for your help

Upvotes: 1

Views: 569

Answers (1)

Simon McArdle
Simon McArdle

Reputation: 893

The simplest method would be to use a MouseEvent listener. You attach the listener to whatever you want to be clicked and tell the listener which function to execute when an event is triggered:

var test:int = 0;

image.addEventListener(MouseEvent.CLICK, thisIsTest);
// Will 'listen' for mouse clicks on image and execute thisIsTest when a click happens

public function thisIsTest(e:MouseEvent):void
{
    test = test + 1;
    trace(test);
}

// Output on subsequent clicks
// 1
// 2
// 3
// 4

This does mean the image you want to attach the listener to needs to be a display object, like a sprite or movieclip, but this shouldn't be a problem if you're using Flash.

EDIT: Further actions noted in comments.

Import an image into Flash and use it to generate a Sprite or Movieclip and give it an Actionscript link id (like a class name):

Import image into library

// Add the image to the stage
var img:myImage = new myImage();
addChild(img);

// Assign the mouse event listener to the image
img.addEventListener(MouseEvent.CLICK, thisIsTest);

Upvotes: 2

Related Questions