while() script conundrum

Hi

To give context, what I’m trying to do is this:

I have two buttons. Hitting on one will activate one object, whilst hitting button 2 will activate the following code, used to display a set of images and cycle through them every three seconds indefinitely until the player hits the other button.

function ShowLocals()
{	
	while (mugShotsOn) 
	{			
		for (var i = 0; i < locals.length; i++)
		{
			locals[i].active = true; //show picture
			guitextLocalNameTag.text = nameTag[i];
			yield WaitForSeconds(3);
			
			locals[i].active = false; //hide picture
			
			if (i== locals.length) {
				i = 0; //reset to the beginning
			}
			
			if (!mugShotsOn) {  //mugShotsOn is set to FALSE when button 1 is pressed
				guitextLocalNameTag.text = "";
				break;
			}
		}
	}
}

The issue I’m having is that if the player hits button 1 then 2 slowly, the above works fine. But, if Button 1 is pressed then 2 is pressed again very quickly, then a second cycle of the above will begin, such that cycle one image 2 will be shown concurrently with cycle two image 1. Both cycles will loop.

I figure it’s got to do with the yield having to play out? I’ve tried various ways to break the loop and the yield, but to no avail so far.

Any advice welcome.

Thanks! :sunglasses:

add a variable to check if the function has already been called:

var isRunning : boolean;

function ShowLocals(){
      if(isRunning) return;
      isRunning = true;
      // loop
      isRunning = false;
}

Thanks Spinal… took some tweaking, but the concept works. Thanks