我一直在尝试使用这个函数在输入触发器时触发声音,但我不能让它工作。我一遍又一遍地读我的代码,没有任何异常,看起来完全像文档所说的那样,所以我就是找不到我的错误。
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
,但声音不能播放。此外,声音本身也工作得很好,音量也很好。
发布于 2020-07-29 02:35:55
它不工作是因为,这是什么?
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);
}
}
}
https://stackoverflow.com/questions/63139748
复制相似问题