コード例 #1
0
    /// <summary>
    /// Plays the given music
    /// </summary>
    /// <param name="musicName"></param>
    public void PlayMusic(string musicName)
    {
        // The create the sound player
        if (this.musicPlayerGO == null)
        {
            this.CreateSoundPlayer();
        }

        // Don't know it
        if (!this.soundClips.ContainsKey(musicName))
        {
            return;
        }

        // Already playing no need to trigger it
        if (this.musicClip.soundName == musicName && this.musicClip.IsPlaying)
        {
            return;
        }

        this.musicClip.Stop();

        // Play and loop the new music
        SoundClip musicClip = this.soundClips[musicName];

        musicClip.SetSource(this.musicPlayerGO.GetComponent <AudioSource>());

        this.musicClip      = musicClip;
        this.musicClip.Loop = true;
        this.musicClip.Play();
    }
コード例 #2
0
    /// <summary>
    /// Spawns a new object with an AudioSource to fire off the sound given
    /// Thus preventing the same sound trying to play twice from the same audio source
    /// Triggers the destruction of the object based on the clip's length
    /// </summary>
    /// <param name="soundName"></param>
    public void PlaySound(string soundName)
    {
        if (this.soundClips.ContainsKey(soundName))
        {
            GameObject soundGO = new GameObject(soundName);
            soundGO.AddComponent(typeof(SoundClip));

            SoundClip soundClip = this.soundClips[soundName];
            soundClip.SetSource(soundGO.AddComponent <AudioSource>());
            soundClip.Play();

            Destroy(soundGO, soundClip.clip.length);
        }
    }