How to make sound play only once on trigger

Hi there,

I have a sound alarm that’s only supposed to trigger when the player enters a trigger collider. However, if the player is within the collider, the sound will constantly loop. If the player passes by it normally, it plays over itself at least twice miliseconds apart and it sounds weird. I only want it to play once whenever a player or any other character walks through it. Here’s my code. What do I need to change?

using UnityEngine;
using System.Collections;

public class storeAlarmScript : MonoBehaviour {
	public bool enter;
	public AudioClip alarm;
	private AudioSource source;

	// Use this for initialization
	void Start () {
		enter = false;
		source = GetComponent<AudioSource>();
	}
	
	// Update is called once per frame
	void Update () {
	
		if (enter == true)
			source.PlayOneShot (alarm);
	}

	void OnTriggerEnter (Collider other)
	{
		if (other.gameObject.tag == "Player") {
			enter = true;
			
		}
		Debug.Log ("Entered");
	}
	
	//Deactivate the Main function when player is go away from alarm spot
	void OnTriggerExit (Collider other)
	{
		if (other.gameObject.tag == "Player") {
			enter = false;
		}
		Debug.Log ("Exited");
	}
}

void Update () {
// Nothing to see here
}

void OnTriggerEnter (Collider other)
{
     if (other.gameObject.tag == "Player") {
         enter = true;
         // Play the sound only on the trigger
         source.PlayOneShot (alarm);             
     }
     Debug.Log ("Entered");
}

int count = 1;

void OnTriggerEnter (Collider other)
 {
      if (other.gameObject.tag == "Player") {
          enter = true;
          // Play the sound only on the trigger
if(enter && count = 1)
{
          source.PlayOneShot (alarm);
count -= 1;

     
}
      }
      Debug.Log ("Entered");
 }
     void OnTriggerExit (Collider other)
     {
         if (other.gameObject.tag == "Player") {
             enter = false;
count = 1;
         }
         Debug.Log ("Exited");
     }
 }

Usually, in my experience, the NullReferenceException is shown in the console if a component is trying to be accessed from a gameObject, but that component is not actually on the gameObject it’s trying to access it from.

I was going to suggest this, but I see it was taken care of in script, I just figured I’d state this in plain English for anyone whom might be like me (I get lazy looking at code sometime :-/). The code you originally posted has the trigger being executed one per frame, and if you are running at say 300 frames per second, then as long as you’re in the trigger, the audio will keep playing once per frame, being overridden each time the next frame is executed. The best way is to use OnTriggerEnter();, so that it only executes when a collision is detected.