Search code examples
c#unity-game-enginetriggersfreezeplaysound

Unity Editor freezes when OnTriggerEnter() plays a sound


My Unity Editor Freezes every time the player enters the trigger,

  • I have added a keycode to see if the audio source is causing it
  • I have commented source.Play() out of the OnTriggerEnter and used a debug statement to check for collisions working properly

both work without a problem so I know it has something to do with OnTriggerEnter() activating the source.

public class PlaySound : MonoBehaviour
{
    public AudioSource source;
    public Collider coll;
    public AudioClip clip;

    public bool soundPlaying;

    private void Start() 
    {
        source = GetComponent<AudioSource>();
        coll = GetComponent<Collider>();
        soundPlaying = false;
    }

    private void Update() 
    {
        while(source.isPlaying)
        {
            soundPlaying = true;
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Space entered");
            source.Play();
        }
    }

    private void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.tag == "Player")
        {
            Debug.Log("player entered");
            source.Play();
        }   
    }
    
}

One more note, the soundPlaying Bool is for an AI to detect the object as there will be a few scattered around.


Solution

  • Nevermind I solved it, the while loop in the update function was likely causing an overflow so I changed it to an if statement and it all works correctly now