Problem with audio files using OnTrigger

Hi all

I’m relatively new to Unity. I’ve been trying to create an NPC which plays a series of audio files when I enter its trigger range. When I go out the trigger and return, I want the audio files to start from scratch. The audio files are running fine for the first time, but when I go out of trigger range and return, some of the files keep repeating. I think this is related to the way I am using the isinTrigger variable, but I’ve been unable to figure out a solution. Can anyone please help me out?

Here is my code:

    function Start()
{
	soundList=Resources.LoadAll("audio",Object);
}


function OnTriggerEnter (other:Collider) 
{
	isinTrigger = true;
	otherObj=other;	
	var i:int=1;
	while(i<=soundList.Length)
	{
			audio.clip=soundList[i-1];
			audio.Play();
			yield WaitForSeconds(audio.clip.length);
			i++;
		
						
	}	
	
				
	
}
function Update()
{
	if(isinTrigger == false)
	{
		
		audio.Stop();
		
	}
	
}

function OnTriggerExit()
{
		isinTrigger = false;
		audio.Stop();
				
}

Your for in the OnTriggerEnter function will keep running and play the remanning audio files even if you leave the trigger area, cause you stop the actual audio but do not prevent the while to keep running the others. I would recommend a code refactoring, but for a fast solution try this:

function OnTriggerEnter (other:Collider) 
{
    isinTrigger = true;
    otherObj=other;    
    var i:int=1;
    while(i<=soundList.Length)
    {
         audio.clip=soundList[i-1];
         audio.Play();
         yield WaitForSeconds(audio.clip.length);

         if (!isinTrigger)
             break;
         i++;
    }  
}