views:

47

answers:

2

The variable currentIndex is declared globally and initialized with a certain value say '0'. How do I hold the value of currentIndex which is incremented every time the function is called? In the given code, every time the function is called, the value is reinitialized.

function nextSong(e:Event):void 
{
        sc.stop();

 currentIndex = currentIndex + 1;

 var nextSongFunc:URLRequest = new URLRequest(songlist[currentIndex].file);
 var nextTitle:Sound = new Sound();
 nextTitle.load(nextSongFunc);
 currentSound = nextTitle;
 sc = currentSound.play();

 sc.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

NextBtn.addEventListener(MouseEvent.CLICK, nextSong);
+1  A: 

You need to declare the variable outside the function. How you do this depends on the context. Where is this function being defined? In the 'actions window' on the timeline in Flash? or inside a <script> block in Flex? or somewhere else?

It looks like you're in the Flash tool, in the actions window. If so, then just do it like this:

var currentIndex:int = 0;

function nextSong(e:Event):void {
  sc.stop();
  currentIndex = currentIndex + 1;

  var nextSongFunc:URLRequest = new URLRequest(songlist[currentIndex].file); 
  var nextTitle:Sound = new Sound(); 
  nextTitle.load(nextSongFunc); 
  currentSound = nextTitle; 
  sc = currentSound.play();

  sc.addEventListener(Event.SOUND_COMPLETE, nextSong); 
}

NextBtn.addEventListener(MouseEvent.CLICK, nextSong);

If that doesn't work, let me know some more details, and we'll sort it out.

Lee
A: 

If you're using Flash CS , you should take advantage of the DocumentClass. In such case you could define currentIndex as a private variable and it will be incremented/decremented in your functions.

This is a much better approach than writing your code in the Actions panel, allows for a lot more flexibility and you don't run into problems due to frame dependent code.

PatrickS