AudioClip仅在Trigger上播放一次

时间:2015-09-07 23:20:11

标签: c# unity3d

在我的游戏中,我在团结中创作我每次在我的一个游戏对象上发生碰撞时都会尝试播放音频剪辑。由于某种原因,音频将在第一次出现碰撞时播放,但从那时起它就不再发出声音了。

与之碰撞的游戏对象具有AudioSource的组件,并且我在该组件中选择了音频剪辑。

以下是我启动音频的代码:

if (PlayerPrefs.GetInt ("Sound Playing", 1) == 1)
{
    audio = GetComponent <AudioSource>();
    audio.Play ();
}

我也尝试过使用PlayOneShot()方法,但它也做了同样的事情。

修改

这里有一个小小的代表,我的游戏在这里做了什么:

public class Ship : MonoBehaviour 
{
    void OnTriggerEnter2D(Collider2D collider)
    {
        Laser laser = collider.gameObject.GetComponent<Laser> ();
        if (laser) 
        {
            if (!immune)
            {
                //update healthbar
                healthbar.hit();

                //reset health boost
                forcefield.resetHealthBoost();


                health -= laser.getDamage(); //remove health from ship

                //create explosion
                GameObject explosion = Instantiate(explode, gameObject.transform.position, Quaternion.identity) as GameObject;
                explosion.GetComponent<ParticleSystem>().startColor = this.GetComponent<SpriteRenderer>().color;

                if (SoundEffects.soundOn && PlayerPrefs.GetInt("Sound Playing", 1) == 1) 
                {
                    audio = GetComponent<AudioSource>();
                    audio.Play();
                }
            }

            laser.hit();//destroy the laser that hit the ship
        }
    }
}

这是为了表明我在检查器中有AudioSource和AudioClip设置(AudioSource附在船上):

enter image description here

3 个答案:

答案 0 :(得分:0)

用音频看起来没问题。可能是碰撞或其他问题。在代码行Debug.Log("Play sound.");之前添加代码audio.Play();,然后测试。

答案 1 :(得分:0)

我的游戏问题是我没有意识到使用gameobject.SetActive(false)后来在我的代码中阻止了第二个音频剪辑无法播放。当船被摧毁时我把它设置为假,这就是问题一直存在的问题。现在工作正常。

答案 2 :(得分:0)

确保您的音频监听器也接近爆炸。它可能很远,可能听不到。还要检查audio.isPlaying,然后播放音频。音频可能仍在播放,您必须正确停止播放。

   if (audio.isPlaying) {
    audio.Stop();       
    audio.Play();
   }

如果所有其他方法都失败了,你可以随时做PlayOneShot(),这基本上就像它说的那样。 audio.PlayOneShot();这可能会有问题,因为如果你把它放在OnTriggerEnter()上,它可能会在短时间内运行多次。你可能听到它口吃,因为它排队了许多爆炸。

最后,不要将PlayerPref用于那些特定的事情。您应该诚实地为游戏特定数据存储保留它。你为什么不能简单地使用isPlaying? PlayerPrefs只会让任务变得非常复杂。我曾经习惯使用PlayerPrefs将数据从C#传输到UnityScript。最后,几乎最好使用静态变量,或者创建一个Singleton类并将值提交给各种实例。另外,我了解到在调整编译顺序时我可以使用跨语言的方法和变量。有点偏离主题,但仍然非常重要。