Unity Ninja Unity 3D Forum
To have exclusive access to all downloads, recourses and links within this forum, a free registered account is required. Just a heads up Wink

You are not connected. Please login or register

Unity Ninja Unity 3D Forum » FREE Project Downloads & Recources » Scripts » Script for Play Music Random for Unity 5.X good for Horror Game

Script for Play Music Random for Unity 5.X good for Horror Game

View previous topic View next topic Go down  Message [Page 1 of 1]

PitbullM


Member [Lv. 3]
Member [Lv. 3]
Hello
I decided to create a randomly script that would allow you to play music in the background.
Ideal for horror games or investigative.
Just drag the script inside an object, indicate the number of tracks and drag them inside.
Good fun. Very Happy


Code:

/*                        
 *                   Copyright © 2016 Digital_Pitbull
 *                              for
 *                   @ Unity Ninja Forum
 *                        
 *                   @ Author - PitbullM
 *
 *                   @ Date - October 2016            
 *                          
 *        Play Music Random for Unity 5.X good for Horror Game
 */

using UnityEngine;
using System.Collections;




public class Music_Random : MonoBehaviour
{

    AudioSource audio;
    float alpha = 1.0f;
    public  AudioClip[] PlayList;
    public float fadeSpeed = 2.0f;
 


    void Awake()
    {
        audio = GetComponent<AudioSource>();
        
    }

    void Start()
    {
 if (!audio.playOnAwake)
 audio.clip = PlayList[Random.Range(0, PlayList.Length)] as AudioClip;
        audio.Play();
        StartCoroutine(Fade());
    }

  
    void Update()
    {

        if (!audio.isPlaying)
        {
            playRandomMusic();
            StartCoroutine(Fade());
        }
    }

    void playRandomMusic()
    {
        audio.clip = PlayList[Random.Range(0, PlayList.Length)] as AudioClip;
        audio.Play();
    }

    void OnGUI()
    {
        GUIStyle myStyle = new GUIStyle(GUI.skin.GetStyle("label"));
        myStyle.fontSize = 17;      
        GUI.color = new Color(255, 255, 0, alpha);
        GUI.Label(new Rect(15,60,500,200),"Play Song: "+"["+audio.clip.name+"]",myStyle);
        
    }

    IEnumerator Fade()
    {
        alpha = 0;
        while (alpha < 1f)
        {
            alpha += Time.deltaTime * fadeSpeed;
            yield return null;  
        }
        StartCoroutine(FadeOUT());
    }

    IEnumerator FadeOUT()
    {
        
        yield return new WaitForSeconds(10);
        Debug.Log("FadeOUT");
        while (alpha > 0f)
        {
            alpha -= Time.deltaTime * fadeSpeed;
            yield return null;
        }

    }

    }

View user profile

View previous topic View next topic Back to top  Message [Page 1 of 1]

Permissions in this forum:
You cannot reply to topics in this forum