Strange sound distortions because of coding problem.

Hi, I’m just trying to make it that when an NPC called pilot moves to a certain location, an audio clip plays once. As it is, when the NPC is in position the audioclip plays in a crazy loop like a machine gun.
Any advice would be great.

    public GameObject pilot;
    public AudioClip TooLoud;
    public GameObject player;
    //public float DistSound = 3;
    public GameObject SoundSource;
  

    // Use this for initialization
    void Start()
    {
        SoundSource.GetComponent<AudioClip>();
        SoundSource.GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        if (pilot.transform.position.y < 0.8)
           
            /*(Vector3.Distance(player.transform.position, pilot.transform.position) < DistSound)*/
        {

            SoundSource.GetComponent<AudioSource>().PlayOneShot(TooLoud);
       

        }
    }
}
if (pilot.transform.position.y < 0.8)

Yeah, so that keeps being false for multiple frames and you keep playing a new clip every frame.

So set a flag and only play the clip if you haven’t played the clip already.

public bool playedClip = false;
...

if (pilot.transform.position.y < 0.8) {
..
} else if (!playedClip) {
     playedClip = true;
     soundSource.GetCompon...
}
1 Like