What do I want to achieve? I am currently trying to make a highlight cycle system with Q and E keybinds that fires between the server and the client. Every time the player presses Q or E, a GUI will cycle at the bottom to the next color incase the player forgets.
What is the issue? I have a local counter script which goes to the server and changes the highlight of the player’s character. For whatever reason on the server script, every time I die, the number of times the function runs increases. I was able to figure this out from the output going “1” to “1 1” to “1 1 1.” Another issue that might be caused by this are my tweens not running for the GUIs when being sent back to the client.
Local script for cycling between Q and E with a counter
The problem is the fact that you’re establishing new Event Connections inside the CharacterAdded event. This means that everytime that event is fired, more connections are created and the pre-existing connections will continue to fire as well.
Store the RBXScriptConnections to different variables and disconnect them when the player dies.
-- Example
local connection = Instance.Signal:Connect(function()
--...
end)
--...
connection:Disconnect() -- the connection is disconnected and will no longer run
I implemented the disconnection on death, but I don’t exactly know how to deal with implementing the connection or how I should fit it into my script due to the fact that I’ve never messed with this before.
I’d appreciate if you could send a video tutorial on this or rewrite how I’d implement it.
This is how you would store the connections into variables:
local redConnection = nil -- where the connection will be stored
Player.CharacterAdded:Connect(function()
if redConnection then -- check if a connection was already created
redConnection:Disconnect() -- disconnect the old connection
end
--...
redConnection = RemoteEvent.OnServerEvent:Connect(R) -- establish the connection and store it to the variable
end)
Alternatively, you can store the connections in a table:
local connections = {} -- list where the connections will be stored
Player.CharacterAdded:Connect(function()
for _, connection in connections do -- loop through the `connections` list
connection:Disconnect() -- disconnect any old connections
end
--...
table.insert(connections, RemoteEvent.OnServerEvent:Connect(R))
-- insert the RBXScriptConnection into the `connections` table, to be disconnected later
end)