加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 播放音频并播放更多内容

发布时间:2020-12-15 23:32:55 所属栏目:百科 来源:网络整理
导读:我正在用C#进行团结的小游戏. 到目前为止,我已设法设计级别并完成一些基本脚本. 目前我有一个触发器,它产生一个对象,并希望它一旦用户进入就播放和音频源.但是,因为我希望它是一个跳跃恐慌,触发器非常小,目前声音只播放IF我留在触发器. 我的代码如下: using
我正在用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);
    }

}

我想知道是否有一种方法可以在人们离开扳机后保持声音播放.

谢谢!

解决方法

附加的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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读