Script will not disable

I made a script that after it finished it disables itself. It does disable itself, but the script still runs.

local Red = game.Teams.Red
local Blue = game.Teams.Blue
local textButton = script.Parent
local player = game.Players.LocalPlayer


game:GetService("UserInputService").InputBegan:connect(function(inputObject, gameProcessedEvent)
		    if inputObject.KeyCode == Enum.KeyCode.P then 
		local team = math.random(1,2)

		if team == 1 then
			player.Team = Red
		end
		if team == 2 then
			player.Team = Blue
		end
		player.Character.Humanoid.Health = 0
		game.StarterGui.ScreenGui.Frame.LocalScript.Disabled = true
	 end
end)

It’s in a local script so it runs for the client only.

RBXScriptSignals creates a separate thread which is different from the thread the script uses. They will keep running even if you disable the script. To disable connection events, assign the connection to a variable and use :Disconnect to disable the connection.

1 Like

Sorry could you explain a bit more?

Connections are entirely separate from the script it was created in. They will continue to run until they are explicitly disconnected, either when the instance they are connected to gets destroyed or with the :Disconnect() function.

You can read this article to understand how to disconnect events:

Try this:

local Red = game.Teams.Red
local Blue = game.Teams.Blue
local textButton = script.Parent
local player = game.Players.LocalPlayer

local connection
connection = game:GetService("UserInputService").InputBegan:connect(function(inputObject, gameProcessedEvent) --assigns the connection to a variable
		    if inputObject.KeyCode == Enum.KeyCode.P then 
		local team = math.random(1,2)

		if team == 1 then
			player.Team = Red
		end
		if team == 2 then
			player.Team = Blue
		end
		player.Character.Humanoid.Health = 0
		connection:Disconnect() --disconnects the connection so it doesn't run anymore
	 end
end)

Try setting the players’ TeamColor, rather than the Team.

Huh cool. I didn’t know that! Well it works, thanks!

Also could I do this? :Reconnect()

I think it’s :Enable() just so you know.

1 Like