AudioSource 在 GameObject 被销毁之前不播放

AudioSource not playing before GameObject is destroyed

在此程序中,当点击开火按钮时,它会创建一个激光对象,然后飞过屏幕,当它击中坏人对象时,会播放爆炸声并删除激光和坏人对象.

我无法让它播放爆炸声,但它确实删除了两个对象并且没有抛出任何类型的错误。我把爆炸声附加到坏人身上,并说在对象被摧毁之前播放坏人的AudioSource

using UnityEngine;
using System.Collections;

public class LaserFire : MonoBehaviour {

    public float laserSpeed = 10f;

    // Use this for initialization
    void Start () {
        //when the shot is fired, play the sound effect for a shot fired
        GetComponent<AudioSource>().Play();
    }

    // Update is called once per frame
    void Update () {
        //moves the object across the screen over time
        transform.Translate(0f, laserSpeed * Time.deltaTime, 0f);
    }

    void OnTriggerEnter2D(Collider2D hitObject)
    {
        //if the laser hits a bad guy, play the audio clip attached to the bad guy
        hitObject.GetComponent<AudioSource>().Play();
        Destroy(hitObject.gameObject);
        Destroy(gameObject);
    }
}

这里的问题是,虽然 AudioSource 播放成功(因为没有错误),但它在声音片段实际播放很远之前就被破坏了。开始播放后,您 Destroy() 关联 GameObject,这会立即停止播放。

要解决这个问题,请考虑使用 AudioSource.PlayClipAtPoint():

void OnTriggerEnter2D(Collider2D hitObject)
{
    //if the laser hits a bad guy, play the audio clip attached to the bad guy
    AudioSource hitAudio = hitObject.GetComponent<AudioSource>();
    AudioSource.PlayClipAtPoint(hitAudio.clip, transform.position);
    Destroy(hitObject.gameObject);
    Destroy(gameObject);
}

此方法将实例化一个带有 AudioSource 的临时对象,播放它,并在播放结束后销毁它。因此,如果您的规模增加,您应该留意您对这种方法的使用;由于生成垃圾,它可能会造成性能问题,因此 object pooling 可能更适用。