c# - 如何在 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
预期,但声音不播放。此外,声音本身也很好,音量也很好。
解决方案
它不起作用,因为这是什么?
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);
}
}
}
推荐阅读
- c - 'close' 的静态声明遵循非静态声明 static inline int close(int sock)
- c# - C# 从文件中读取 - 整数并忽略其他所有内容
- d3.js - d3可以将鼠标悬停事件传递给下面的图层吗?
- java - Appium - 创建会话 - 错误:应提供 JSONWP 或 W3C 功能
- php - 从数字格式中删除逗号而不删除 PHP 中的小数点
- vb.net - 覆盖接口字段
- c++ - c++赋值英寸到厘米换算表
- python - 在python中读取资源文件
- python - ND 数组中的 Numpy 一维数组操作
- loops - 具有循环不变代码运动的解析器示例