首页 > 解决方案 > 当 OnTriggerEnter() 播放声音时 Unity 编辑器冻结

问题描述

每次玩家进入触发器时,我的 Unity 编辑器都会冻结,

两者都可以正常工作,所以我知道这与 OnTriggerEnter() 激活源有关。

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();
        }   
    }
    
}

还有一点需要注意的是,soundPlaying Bool 是为了让 AI 检测物体,因为周围会有一些散落的物体。

标签: c#unity3dtriggersfreezeplaysound

解决方案


没关系,我解决了它,更新函数中的while循环可能导致溢出,所以我将其更改为if语句,现在一切正常


推荐阅读