首页 > 解决方案 > 如何在 Unity 上使用 PlayOneShot()?

问题描述

我一直在尝试使用此功能在输入触发器时触发声音,但我无法使其工作。我已经阅读并阅读了我的代码,似乎没有任何问题,看起来与文档所说的完全一样,所以我无法弄清楚我的错误。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class footsteps_script : MonoBehaviour
{

    public GameObject soundObject;
    public GameObject trigger;
    private AudioClip clip;
    public bool nextTrig;

    void Start()
    {
    nextTrig = false;
    clip = soundObject.GetComponent<AudioClip>();
    }

    void OnTriggerEnter ()
    {

        if (Bunny_script.nextTrig == true)
        {
        
            soundObject.GetComponent<AudioSource>().PlayOneShot(clip);
        nextTrig = true;
        trigger.SetActive(false);
        }
    }



  

    
}

AudioSource 附加到另一个对象。触发器应该在另一个事件发生后播放声音。触发器部分工作正常,因为 nextTrig 设置为true预期,但声音不播放。此外,声音本身也很好,音量也很好。

标签: c#unity3d

解决方案


它不起作用,因为这是什么?

 clip = soundObject.GetComponent<AudioClip>();

没有称为 AudioClip 的组件。对于音频剪辑,将其从预制件直接获取到脚本,或者如果您想从 soundObject 中的音频源获取它,那么它将如下所示:

 clip = soundObject.GetComponent<AudioSource>().clip;

稍后您将使用 PlayOneShot 播放它,这将浪费时间,因为您正在播放最初取自该音频源的同一剪辑。实际上只需要这条线来播放它

  soundObject.GetComponent<AudioSource>().Play();

最后,如果您尝试从预制件中获取脚本中的音频剪辑,您的代码将如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class footsteps_script : MonoBehaviour
{

    public GameObject soundObject;
    public GameObject trigger;
    public AudioClip clip;
    public bool nextTrig;

    void Start()
    {
       nextTrig = false;
       //don't forget to assign the your audio clip to the script from the prefabs
    }

    void OnTriggerEnter ()
    {

        if (Bunny_script.nextTrig == true)
        {
            if (clip =! null)
            soundObject.GetComponent<AudioSource>().PlayOneShot(clip);
            nextTrig = true;
            trigger.SetActive(false);
        }
    } 

  }

如果您已经在音频源中拥有附加到声音对象的音频剪辑,那么您的代码将是:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class footsteps_script : MonoBehaviour
{

    public GameObject soundObject;
    public GameObject trigger;
    public bool nextTrig;

    void Start()
    {
       nextTrig = false;
    }

    void OnTriggerEnter ()
    {

        if (Bunny_script.nextTrig == true)
        {
            soundObject.GetComponent<AudioSource>().Play();
            nextTrig = true;
            trigger.SetActive(false);
        }
    } 

  }

推荐阅读