AudioSource在GameObject被销毁之前没有播放

时间:2016-04-03 03:25:38

标签: c# unity3d unity5 audio-player

在此过程中,当点击开火按钮时,它会创建一个激光对象然后飞过屏幕,当它碰到坏人物体时,它会发出爆炸声并删除激光和坏人物体。 / p>

我不能让它播放爆炸声,但它会删除这两个对象并且不会抛出任何类型的错误。我把爆炸声贴在那个坏人身上,然后说在对象被摧毁之前扮演坏人的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);
    }
}

1 个答案:

答案 0 :(得分:2)

这里的问题是虽然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可能更适用。

相关问题