Script not working

I’m having trouble with this script I wrote. When I click the button for the first time, it works but when I click it again, the first coroutine keeps running.

Script:

local btn = script.Parent
local players = game:GetService("Players")
local showing = true


function nametagSwitch(onOrOff)
	for i, plr in pairs(players:GetPlayers()) do
		local character = plr.Character
		if not character or not character.Parent then
			character = plr.CharacterAdded:wait()
		end
		local head = character:WaitForChild("Head")
		local nametag = head:WaitForChild("Nametag")

		if onOrOff == "on" then
			nametag.Enabled = true
		elseif onOrOff == "off" then
			nametag.Enabled = false
		end
	end
end


local show = coroutine.create(function() 
	while true do
		print("on")
		wait()
		nametagSwitch("on")
	end
end)

local hide = coroutine.create(function() 
	while true do
		print("off")
		wait()
		nametagSwitch("off")
	end
end)


------------------------------------------------------------------------------------------


btn.MouseButton1Click:Connect(function()
	if showing == false then
		showing = true
		btn.Text = "Hide Names"
		
		coroutine.resume(show)
		coroutine.yield(hide)
	elseif showing == true then
		showing = false
		btn.Text = "Show Names"
		
		coroutine.resume(hide)
		coroutine.yield(show)
	end
end)

Have you considered using task.cancel?

Here I rewrote the code again if it helps.

local players = game:GetService("Players")

local btn = script.Parent
local showing = true

local function getnametag(player: Player)
	local character = player.Character
	if typeof(character) == 'Instance' then
		local head = character:FindFirstChild("Head")
		if typeof(head) == 'Instance' and head:IsA("BasePart") then
			return head:WaitForChild("Nametag")
		end
	end
end

local function nametagSwitch(set: 'on' | 'off')
	for _, player in pairs(players:GetPlayers()) do
		local nametag = getnametag(player)
		if typeof(nametag) == 'Instance' and nametag:IsA("BillboardGui") then
			nametag.Enabled = set == 'on'
		end
	end
end

btn.MouseButton1Up:Connect(function()
	showing = not showing
	btn.Text = (showing and 'Hide ' or 'Show ') .. 'Names'
	if showing then
		while showing do
			print'on'
			task.wait(0)
			nametagSwitch('on')
		end
	else
		while not showing do
			print'off'
			task.wait(0)
			nametagSwitch('off')
		end
	end
end)
1 Like

I tried it and it works, thank you