So I've got a hopefully easy question, but I don't understand why my code isn't doing what I want it to.
function Sound:load()
trackToPlay = musicDownbeat
trackToPlay:play()
end
function Sound:changeMusic()
if trackToPlay == musicUpbeat then
trackToPlay:stop()
trackToPlay = musicDownbeat
trackToPlay:play()
end
if trackToPlay == musicDownbeat then
trackToPlay:stop()
trackToPlay = musicUpbeat
trackToPlay:play()
end
end
So I've got two Source tracks that can be alternated between, musicUpbeat and musicDownbeat, and at this point in the code (I have stripped down Sound:load() to make it as clear as possible), every time changeMusic() is called, trackToPlay is always musicDownbeat, meaning that every time changeMusic() is called, the music stops and is changed to musicUpbeat.
Sound:load() is only called once, right? So why are my trackToPlay changes not being saved?
The problem is in the function changeMusic
. You need to use elseif
instead of two if
statements. Your code should look like this:
function Sound:changeMusic()
if trackToPlay == musicUpbeat then
trackToPlay:stop()
trackToPlay = musicDownbeat
trackToPlay:play()
elseif trackToPlay == musicDownbeat then
trackToPlay:stop()
trackToPlay = musicUpbeat
trackToPlay:play()
end
end
The way you have written it in your original code, if trackToPlay
is musicUpbeat
(it will be after changeMusic
is called the first time), it will be changed into musicDownbeat
by the first statement, and then immediately changed into musicUpbeat
by the second if
statement.