문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top