Audio play code doesn't change audio

Hey guys, so I am trying to make a code that works like a radio station. You press ‘M’ to start playing a song, and then if you press ‘M’ again it plays another song. Well I have it so that when you press ‘M’ a song plays, but it isn’t the first song in the list, and everytime I press ‘M’ it just keeps playing the song, and particles I have attached to it. Here is my code, please help me so that when you press ‘M’ it plays the first song, then another press plays the second song. Thanks.

public var JustDrive : AudioClip;
public var Song2 : AudioClip;
public var Song3 : AudioClip;
public var Song4 : AudioClip;

public var songcounter : int = 0;

private var offset : Vector3;
private var fwd : Vector3;
private var clone : GameObject;
var unit : float = 0.0f;
var location : Transform; 
public var prefabObject : GameObject;
var canPlaceObject : boolean = true;

function Update()
{
PlayAudio();
}
 
function PlayAudio()
{
if(Input.GetKey(KeyCode.M)){
fwd = transform.TransformDirection(Vector3.forward) * unit;
        offset = transform.position; // + fwd;
        if(canPlaceObject)
        {
            clone = Instantiate(prefabObject, offset, transform.rotation);
            
        }  
        
if(songcounter == 0){
audio.PlayOneShot(JustDrive);
songcounter = 1;
}
 
if(songcounter == 1){
audio.PlayOneShot(Song2);
songcounter = 2;
}
 
if(songcounter == 2){
audio.PlayOneShot(Song3);
songcounter = 3;
}
 
if(songcounter == 3){
audio.PlayOneShot(Song4);
songcounter = 1;
}
 
}
}

2 Answers

2

put it into else if

No that doesn't work, it doesn't play any song doing that.

you have to assign the AudioSource the clip first before you play it. first Put

PlayAudio();

in the start function. then use

audio.clip = Song2;

too assign the audio source your new song then play that new song after you assign it

Another thing that I noticed is that the song numbers are being updated

after you play a song. It looks as if your trying to play all the song in a row like a ‘loop’ or something.