Kin*_*pud 3 c# unity-game-engine
我正在用C#进行团结的小游戏.
到目前为止,我已设法设计级别并完成一些基本脚本.
目前我有一个触发器,它产生一个对象,并希望它一旦用户进入就播放和音频源.但是,因为我希望它是一个跳跃恐慌,触发器非常小,目前声音只播放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<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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种方法可以在人们离开扳机后保持声音播放.
谢谢!
附加的GameObject音频在音频播放完毕之前被销毁.使用AudioSource.PlayClipAtPoint将创建和销毁Audiosource使得缓存aud无用.此外,如果你有太多的触发游戏对象,那将会很慢因为GC.使用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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |