Increment global variable on click in flash, actionscript 3
Making a flash page that can cycle through these three images on mouseclick. For some reason the local changes to count are not reflected on the global one. I tried _global but the syntax was odd and gave me errors. How should I implement this?
import flash.events.Event;
var images:Array = ["images/image.jpg", "images/image2.jpg", "images/image3.jpg"];
var count:int = 0;
forward.addEventListener(MouseEvent.CLICK, loadPhoto);
function loadPhoto(evt:Event){
if(count>2){
count = 0;
}
trace(count);
imageFrame.source = imag开发者_开发技巧es[count];
count++;
}
A simplified version of the problem would be getting trace to output the number of times you've clicked.
import flash.events.Event;
var count:int = 0;
forward.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(evt:Event)
{
trace(count);
count++;
}
I think your issue is a scope one. Try this instead:
import flash.events.Event;
var images:Array = ["images/image.jpg", "images/image2.jpg", "images/image3.jpg"];
var count:int = 0;
forward.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(evt:Event)
{
loadPhoto(); // Notice, this is calling a function already defined on root!
}
function loadPhoto()
{
trace(count);
// Use modulous to deal with this type of behavior -- it is easier in the end.
imageFrame.source = images[count%images.length];
count++; // Count should be within scope here.
}
Any chance that the code is in a frame that is executing multiple times? (because you missed a stop() somewhere, for example)
If so, you might have a problem you hadn't noticed which is causing this strange behaviour. A simple way to check if this is happening is adding a trace("test")
after declaring count
(or before, but put it in that frame script).
This should work fine. I'm assuming by the way the code is written, this is on the timeline and not in a class. It shouldn't make any difference -
However try referencing the "count" variable inside your function with the this
It may look something more like:
function loadPhoto(evt:Event){
if(this.count>2){
this.count = 0;
}
trace(this.count);
imageFrame.source = images[this.count];
this.count++;
}
It's more verbose and pedantic, but your initial code should work just fine. I might add - this code doesn't use the 'count' variable outside the function, alternative to declaring it - is the problem, the counter is always '0' when the function is run?
精彩评论