- Home /
How do I randomize my Music played? The opening song is always the same song and I don't know why.
I made a Script which plays music every 2 to 5 minutes. Each time, the music gets randomly picked from the public AudioClip[] MusicClips
array. The Line MusicSource.clip = MusicClips[Random.Range(0, MusicClips.Length)];
in the method PlayMusic()
always picks a random Song from the Array before it gets played.
My only Problem: Despite randomness, the first song that plays when the game starts, is always the 1st Song from my array. Never does the game start with the 2nd, 3rd, or any further Array element. It's always the 1st, but it's not supposed to be only the 1st.
How do I also randomise the opening song and not just any song after?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicSystem : MonoBehaviour
{
public AudioClip[] MusicClips;
public AudioSource MusicSource;
// Start is called before the first frame update
void Start()
{
StartCoroutine (MusicTimer()); //Start Music
}
// void Update() { if (Input.GetKeyDown(KeyCode.F5)) { PlayMusic(); } } //This Line of Code is for Debug Purposes
IEnumerator MusicTimer()
{
yield return new WaitForSeconds(1); //Wait 1 Second
PlayMusic();
yield return new WaitForSeconds(Random.Range(120, 300)/*2 to 5 Minutes*/); //Wait Until Next Song
StartCoroutine (MusicTimer()); //Restart this Coroutine so you can hear the next Song after some more time
}
void PlayMusic()
{
MusicSource.clip = MusicClips[Random.Range(0, MusicClips.Length)];
MusicSource.Play(); //Play Music
}
}
The Script is on this Game Object:
Answer by $$anonymous$$ · Jun 23, 2019 at 02:22 PM
Oops! Even the Opening Song IS randomized! For me, it just did not happen to choose the 2nd or 3rd Song until now!
Your answer
Follow this Question
Related Questions
Random.Range is not changing? 1 Answer
How to put Random.range in float array? 3 Answers
Is there a better way for randomization for triggering a percentage of the time 1 Answer
Randomize values without exceeding a value? 3 Answers
How to make certain elements in an array rarer when using random selection? 4 Answers