- Home /
Toggling through music
Want to be able to toggle through different songs in game when pressing a button (EX:P)
i tried a switch, but it got me lost quicky.
Script:
var Music =GameObject[]; // Array of different Musicthat are used.
function Update() { switch(Music){ case 1: if (Input.GetKeyDown("q") ){ Music.audio.Play; break; }
what can i do? Thanks! :{D
Answer by · Sep 10, 2010 at 01:48 AM
You don't need a switch to do this. You will need an AudioSource on the object you attach this script to. (Code is untested, but partially based on recent answer on how to pick a random song)
var myPlaylist : AudioClip[]; var nextSong : int = 0;
function Update () { if ( Input.GetKeyDown("p") ) // 'p' has been pressed PlayNextSong(); // play the next song }
function PlayNextSong () { if ( audio.isPlaying ) // if there is audio playing audio.Stop(); // stop it
audio.clip = myPlaylist[nextSong]; // set the audio clip to the next in the array audio.Play(); // start the 'nextSong' playing
if ( nextSong < myPlaylist.length-1 ) // if the 'nextSong' is not the last in the array nextSong += 1; // add one to the index else // otherwise nextSong = 0; // set the nextSong to the first in the array }
Thank you so much, but i have a problem with it. When it gets to the very last song it just activates the pause button and nothing else.
Do you get any errors? I don't know why it would activate the pause button.
i get this
IndexOutOfRangeException: Array index is out of range.
Apologies, the 'myPlaylist.length' check needed to subtract one before comparing.
Your answer
Follow this Question
Related Questions
Enable/Disable Object and Music? 1 Answer
Audio Source will not "unmute" after toggling? 2 Answers
Object not surviving on load? 1 Answer
UI Toggle Component Broken? 0 Answers