播放音频并播放更多内容
我用C#在团结5中制作一个小游戏。
到目前为止,我已设法设计级别并完成一些基本脚本。
目前我有一个触发器产生一个对象,并希望它一旦用户输入就播放和音频源。 然而,因为我希望它是一个跳跃恐慌,触发器非常小,目前声音只播放IF我留在触发器。
我的代码如下:
using UnityEngine; using System.Collections; public class Spawner : MonoBehaviour { public GameObject monster; public AudioSource aud; public AudioClip piano; void Start () { monster.SetActive (false); aud = monster.GetComponent(); } void OnTriggerEnter(Collider other){ if (other.CompareTag ("Player")) { monster.SetActive (true); AudioSource.PlayClipAtPoint(piano, monster.transform.position); } } void OnTriggerExit(Collider other){ if (other.CompareTag ("Player")) { monster.SetActive (false); } Destroy (this.gameObject); } }
我想知道是否有一种方法可以在人们离开扳机后保持声音播放 。
谢谢!
附加的GameObject音频在音频播放完毕之前被销毁。 使用AudioSource.PlayClipAtPoint
将创建和销毁Audiosource
,这使得缓存aud
无用。 此外,如果您有太多触发游戏对象,由于GC
,这将会很慢。 使用Coroutine
并等待音频完成播放然后销毁gameObject
。
public GameObject monster; public AudioSource aud; public AudioClip piano; void Start() { monster.SetActive(false); aud = GetComponent(); } void OnTriggerEnter(Collider other) { if (aud.isPlaying) { return; //Exit if Audio is already playing } if (other.CompareTag("Player")) { monster.SetActive(true); aud.PlayOneShot(piano); } } void OnTriggerExit(Collider other) { if (other.CompareTag("Player")) { monster.SetActive(false); } StartCoroutine(waitForAudioThenDestroy()); } IEnumerator waitForAudioThenDestroy() { //Wait until we are done playing while (aud.isPlaying) { yield return null;//Don't freeze } //We are no longer playing audio so we can destroy this gameObject now Destroy(this.gameObject); }
您的问题是在声音完成播放之前,您正在OnTriggerExit
函数中删除gameObject
附加到的OnTriggerExit
。 解决此问题的一种简单方法是将AudioSource
附加到您的monster
,然后从那里访问它。 这将有效,因为你不是在摧毁怪物。 我认为您需要更改的是(在将AudioSource
移动到AudioSource
中的monster
之后):
void Start () { monster.SetActive (false); aud = monster.GetComponent(); }
另一种甚至更快的方法是在OnTriggerEnter
方法中调用PlayClipAtPoint
:
IEnumerator OnTriggerEnter(Collider other){ if (other.CompareTag ("Player")) { monster.SetActive (true); AudioSource.PlayClipAtPoint(piano, monster.transform.position); } }
由于这是一种静态方法,因此您可以完全删除aud
音频源。 AudioSource.PlayClipAtPoint
工作原理是在您指定的点( monster.transform.position
)中实例化一个新的AudioSource
组件,播放指定的剪辑( piano
),然后在剪辑完成播放后删除AudioSource
。
编辑:另外,我不认为您的OnTriggerEnter
方法需要IEnumerator
的返回类型,因为您没有在方法中的任何位置使用yield
关键字。 您可以简单地将其更改为具有void
返回类型。 但是,这不会影响代码的function。
编辑2:我愚蠢地忽略了你将怪物设置为不活动的事实。 我认为在这种情况下你最好的选择是使用PlayClipAtPoint
。