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

Why isn't this GUI script working right?

So, I'm making a really crude run GUI with a stamina system. It increases your speed and everything, but it won't decrease the stamina value. Output didn't give me anything on the script. Can someone please help me?

Here's the script:

local running = false
local Character = script.Parent.Parent.Parent.Parent.Character
local left = 100

function onButtonClicked()
if running == false and left > 0 then
	running = true
	Character.Humanoid.WalkSpeed = 25
	script.Parent.Text = "Walk"
end
end

while running == true and left > 0 do ---This is probably where the issue is located.
	left = left - 1
	wait(0.5)
end

while running == true and left == 0 do
	running = false
	script.Parent.Text = "Run"
	Character.Humanoid.WalkSpeed = 16
end

while running == true do
	running = false
	Character.Humanoid.WalkSpeed = 16
	script.Parent.Text = "Run"
end

while running == false and left < 100 do
	left = left + 1
end

script.Parent.Parent.Bar.Text = ""..left

script.Parent.MouseButton1Click:connect(onButtonClicked)

1 answer

✓ Accepted answer

You don't want to have a bunch of sequential while loops.

Once they stop, they won't ever start again.

(It's also problematic that you have the connection after them).

Instead, use one constant, never-ending loop (while true do) that looks at whether or not you are currently running.

(Note that you don't usually want while loops without waits in them like you have -- otherwise it gets too ambitious and checks as quickly as possible -- tens of thousands of times a second -- and will crash ROBLOX)

local running = false
local Character = script.Parent.Parent.Parent.Parent.Character
local left = 100

function onButtonClicked()
	running = not running -- I'm guessing you want this to "toggle" running
	-- If I was running, stop running
	-- If I wasn't running, start running.
end


script.Parent.MouseButton1Click:connect(onButtonClicked)

while true do
	wait(0.5) -- Twice a second, do all this:
	script.Parent.Parent.Bar.Text = tostring(left)
	-- (Though converting to a string shouldn't be necessary for this)
	if left <= 0 then
		-- Out of stamina
		-- Force them to stop running
		running = false
	end
	if running then
		-- I'm running, spend stamina
		left = left - 1
		Character.Humanoid.WalkSpeed = 25
		script.Parent.Text = "Walk"
	else
		-- I'm not running, regenerate
		left = left + 1
		Character.Humanoid.WalkSpeed = 16
		script.Parent.Text = "Run"
	end
end

1 comment

0

Thanks. Just had to do some minor changes, but it works. Once again, thanks.

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