How to make OnTriggerExit

Hi guys. I make one educational game with unity and kinect and I have 3d models of books in one series. I want if trigger enter to play audio, else trigger exit don’ t play audio.

If I don’t have the trigger exit all work good, but if my user touch more than one books at the same time listen the two audio together.

var triggerOn : boolean = false;
var BookAdd:AudioClip;

function OnTriggerEnter (other : Collider) 
{
   if(other.gameObject.name == "LeftGloves"|| "RightsGloves" || "LeftShoe" || "RightShoe")
    {	triggerOn = true;
 		audio.clip = BookAdd;
			audio.Play();
   	}	
   	  function OnTriggerExit()
     { triggerOn  = false;
		}
   	  
  }

Can you help me to find the wrong OnTriggerExit(); Thanks

Well, the first thing you need to specify is what you’re trying to achieve. From what you wrote, that seems like:

  1. Audio to play when the user moves something to collide with the trigger of a book.
  2. Audio to stop playing when the user moves out of the trigger.
  3. If the user collides with two triggers, the most recent trigger should play.

The code you provided had a nesting bug where OnTriggerExit was defined inside of OnTriggerEnter. They should be separate declarations.

Now, only playing one clip at a time is a trickier thing. You’d probably be best suited with a shared AudioSource component that all books referenced and that could be stopped and the clip re-assigned when you entered a new trigger, and could be stopped if, on trigger exit, the clip that was playing was the clip for the book. I’ve mocked up an example below.

// Defined in inspector, points to an AudioSource component 
// on a GameObject that all your books should point to.
var audio:AudioSource;
var BookAdd:AudioClip;

function OnTriggerEnter (other : Collider) 
{ 
    if(other.gameObject.name == "LeftGloves"|| "RightsGloves" || "LeftShoe" || "RightShoe") 
    { 
        audio.Stop();
        audio.clip = BookAdd; 
        audio.Play(); 
    } 
}
function OnTriggerExit() 
{
    // Check if the clip from this book is still playing
    if(audio.clip == BookAdd)
    {
        audio.Stop();
    }
}