我正在用 C# 在 unity 5 中制作一个小游戏。
到目前为止,我已经成功设计了关卡并完成了一些基本的脚本编写。
目前,我有一个触发器,可以生成一个对象,并希望它在用户输入后播放并播放音频源。然而,因为我希望它是一个跳跃恐慌,所以触发器非常小,目前只有当我留在触发器中时才会播放声音。
我的代码如下:
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<AudioSource>();
}
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);
}
}
我想知道是否有办法即使在人离开扳机后仍保持声音播放.
Thanks!
在音频完成播放之前,附加的游戏对象音频将被销毁。使用AudioSource.PlayClipAtPoint
将创造和毁灭Audiosource
这使得缓存aud
变得毫无用处。另外,如果你有太多触发游戏对象,那么速度会很慢,因为GC
. Use Coroutine
等待音频播放完毕然后销毁gameObject
.
public GameObject monster;
public AudioSource aud;
public AudioClip piano;
void Start()
{
monster.SetActive(false);
aud = GetComponent<AudioSource>();
}
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)