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)