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
Share
Go down
avatar
{SUPER MEMBER}-LV.4
{SUPER MEMBER}-LV.4
Posts : 53
Points : 1530
Rep : 11
Join date : 2015-01-18
Age : 41
Location : Italia
View user profile

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

on Mon Oct 17, 2016 10:54 pm
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;
        }

    }

    }
Back to top
Permissions in this forum:
You cannot reply to topics in this forum