I've got a bug in my script

I have a security camera system where the player can click a button to go to the next camera. However, if the player exits off the cameras then goes back onto it, rather than just going +1 onto the next camera, it goes +2 every time. Any ideas why? Thanks

local rightArrow = script.Parent.Frame.RightArrow
local camFolder = workspace.CamPositions
local button = script.Parent.Parent.Menu.BackToMenu.Content.Frame.ImageButton
local exit = script.Parent.Frame.Exit
local arena = script.Parent.Arena

local plr = game.Players.LocalPlayer
local char = plr.Character or plr:WaitForChild("Character")
local cam = game.Workspace.CurrentCamera

local number = 1

button.MouseButton1Click:Connect(function()
	

	rightArrow.Visible = true
	exit.Visible = true
	arena.Visible = true
	cam.CameraType = Enum.CameraType.Scriptable
	cam.CFrame = workspace.CamPositions["1"].CFrame
	arena.Text = "Arena "..number
	
	exit.MouseButton1Click:Connect(function()

		rightArrow.Visible = false
		exit.Visible = false
		arena.Visible = false
		cam.CameraType = Enum.CameraType.Custom
		cam.CFrame = workspace.CamPositions["1"].CFrame
		number = 1
	end)
	
	rightArrow.MouseButton1Click:Connect(function()
		if number == 7 then
			cam.CFrame = camFolder["1"].CFrame
			number = 1
			arena.Text = "Arena "..number
		else
			cam.CFrame = camFolder[number +1].CFrame
			number = number +1
			arena.Text = "Arena "..number
		end
		wait(.1)
	end)
end)

You need to disconnect the events after exit is clicked

button.MouseButton1Click:Connect(function()
	

	rightArrow.Visible = true
	exit.Visible = true
	arena.Visible = true
	cam.CameraType = Enum.CameraType.Scriptable
	cam.CFrame = workspace.CamPositions["1"].CFrame
	arena.Text = "Arena "..number

local rightArrowConn = rightArrow.MouseButton1Click:Connect(function()
		if number == 7 then
			cam.CFrame = camFolder["1"].CFrame
			number = 1
			arena.Text = "Arena "..number
		else
			cam.CFrame = camFolder[number +1].CFrame
			number = number +1
			arena.Text = "Arena "..number
		end
		wait(.1)
	end)
	
	exit.MouseButton1Click:Once(function() -- only listens once

		rightArrow.Visible = false
rightArrowConn:Disconnect() -- disconnects the function
		exit.Visible = false
		arena.Visible = false
		cam.CameraType = Enum.CameraType.Custom
		cam.CFrame = workspace.CamPositions["1"].CFrame
		number = 1
	end)
end)
1 Like

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