Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I arrange my code so that the if statements within a function do not run consecutively?

In my code (game.StarterGui.ScreenGui.Frame.LocalScript)

local Transitionnow = false
local shopentrance1 = game.Workspace.Shopintrobutton
local Frame = script.Parent
local Message = Frame:WaitForChild("TextBox")
local musicisplaying = false
local music = game.Workspace.SHOPMusics.Purpleland

function transition()
	if not Transitionnow and not musicisplaying then
		Transitionnow = true
		Frame:TweenPosition(UDim2.new(0,0,0,0))
		Message.Text = "Entering Shop zone"
		wait(1.5)
		Frame:TweenPosition(UDim2.new(0,0,-0.4,0))
		music:Play()
		musicisplaying = true
		Transitionnow = false
	end
	if not Transitionnow and musicisplaying then
		Transitionnow = true
		Frame:TweenPosition(UDim2.new(0,0,0,0))
		Message.Text = "Leaving Shop zone"
		wait(1.5)
		Frame:TweenPosition(UDim2.new(0,0,-0.4,0))
		music:Stop()
		musicisplaying = false
		Transitionnow = false
	end
end

shopentrance1.Touched:connect(transition)

I'm trying to imitate the effect (in Pokemon), where when your character moves to a different area, a sign/gui appears at the top with the name of the area you have just arrived to (ex: in Pokemon FireRed: Route 1, Pallet Town, etc).

The problem I am having is that the gui does tween in and out, and that the music does play, but the music ends immediately after the next if statement. I have no idea how to make it such that:

  • Player steps on brick

  • Brick causes function to run .... which shows the gui tweening in and out

  • Music plays (while Player does not step on brick)

  • Player steps on brick AGAIN

  • Brick -> Function runs -> Gui tweens in and out

  • Music stops

Thank you for your help!

2 comments

0

You might be able to implement wait(music.TimeLength); to make sure the music has finished playing, then call music:Stop();

0

Put them after each other in the script. It will do the first one first. Also, maybe put it a wait()

1 answer

✓ Accepted answer

Use else or elseif -- only the first condition that is met will be executed, rather than each being checked and then executed serially.

I also suggest pulling out common code between different branches. Note that they both check if not Transitionnow and both set Transitionnow = true and Transitionnow = false.

if transitioning then
	return -- "early return"
	-- it's often cleaner to quit early rather than have a big `if`
end

transitioning = true

if musicplaying then
	......
	music:Stop()
	......
else
	......
	music:Play()
	......
end

transitioning = false

1 comment

0

That's a neat use of return, thank you for the help!

This discussion is preserved as it was. New answers, comments, and votes are closed.