How do I make my script return to the start?

Hi, this is probably a really stupid question, but I’m new to scripting and I don’t know how to do what I want to do.

Basically, I want to make a Text Button that is part of an admin gui where you are able to spawn in zombies. I want you to be able to spawn and remove said zombies with the same button, I just need the script to restart once the button has been clicked for the second time

Heres what I have so far:

2 Likes

Set debounce to false after the final task.wait(1) in order to let mouseclicks through.
You’re going to get a few memory leaks with this because you’re running a connection instead a connection (and they are the same connection too, which is unnecessary). You can clean up your code by keeping only 1 connection and storing the number of clicks. Here’s some more optimised code:

local counter = 1
script.Parent.MouseButton1Click:Connect(function()
	if counter % 2 == 1 then -- its odd
		zombieEvent:FireServer()
		script.Parent.BackgroundColor = INSERTBACKGROUNDHERE
		script.Parent.Text = "Add Zombies"
		task.wait(1)
		
	else
		zombieRemoveEvent:FireServer()
		script.Parent.BackgroundColor = INSERTBACKGROUNDHERE
		script.Parent.Text = "Remove Zombies"
		task.wait(1)
	end
	
	counter += 1
end)

By the way, please refrain from sending screenshots of code and instead paste code in code blocks (surround your code with three backticks at the start and end)

2 Likes

Hello, you can use functions to do it.
to make it work you can do like

local deb = false

function ChangeZombies()
	if deb == false then
		deb = true
		-- do code for spawning zombies
	else
		deb = false
		-- do code for despawning zombies
	end
end

every time you call this function it spawns and then despawns, repeating all code.

2 Likes

You can also save a really, really small amount of execution time by doing:

local function changeZombies()
	if not deb then
		-- do code for spawning zombies
	else
		-- do code for despawning zombies
	end
    deb = not deb
end
3 Likes

Thank you so much @Morkich1 and @ValtryekRBLX, I literally would have never figured this out by myself!

2 Likes

No worries! Glad we could help. If you have any further queries, let us know!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.