Example #1
0
    // the Update function will do the fade in/out effect
    void Update()
    {
        // First, if the user want to change the volume
        if (smoothVolume)
        {
            if (status == MusicPlayerStatus.FadingOut || status == MusicPlayerStatus.FadingIn)
            {
                smoothVolume = false;
            }
            else
            {
                // Smooth the volume
                if (smoothVolumeBeginValue < volume)
                {
                    audio.volume = cubicInOut(Time.time - smoothVolumeStart, smoothVolumeBeginValue, volume, smoothVolumeDuration);
                }
                else if (smoothVolumeBeginValue > volume)
                {
                    audio.volume = smoothVolumeBeginValue - cubicInOut(Time.time - smoothVolumeStart, 0f, smoothVolumeBeginValue - volume, smoothVolumeDuration);
                }

                // If time is up we stop the animation
                if (Time.time > smoothVolumeStart + smoothVolumeDuration)
                {
                    audio.volume = volume;
                    smoothVolume = false;
                }
            }
        }

        // Now manage fade out/in
        if (status == MusicPlayerStatus.FadingOut)
        {
            if (Time.time < fadeStart + fadeOut)
            {
                audio.volume = volume - cubicInOut(Time.time - fadeStart, 0f, volume, fadeOut);
            }
            else
            {
                // Effect is finished
                audio.Stop();
                audio.volume = 0f;
                status       = MusicPlayerStatus.Playing;
                // Is there another music to be played?
                if (nextclip != null)
                {
                    audio.clip = nextclip;
                    audio.Play();
                    nextclip  = null;
                    fadeStart = Time.time;
                    status    = MusicPlayerStatus.FadingIn;
                }
            }
        }
        else if (status == MusicPlayerStatus.FadingIn)
        {
            if (Time.time < fadeStart + fadeIn)
            {
                audio.volume = cubicInOut(Time.time - fadeStart, 0f, volume, fadeIn);
            }
            else
            {
                // Effect is finished
                audio.volume = volume;
                status       = MusicPlayerStatus.Playing;
            }
        }
        if (!audio.isPlaying && audio.loop == false)
        {
            if (IsCache)
            {
                PoolManager.AddGameObject(gameObject.name, gameObject);
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }