Player's humanoid remains as part of script after player has walked off of the platform

I am currently working on a system to kick players via a GUI that a security officer has, but when the officer clicks the kick button, it kicks everyone that has stood on the platform. Is there a way to remove a player’s humanoid from the part as soon as they step off of the part?

Additionally, the touched function that I am using isn’t working the entire time a player is on the platform, only a split second when it touches it and then it touchends.

script.Parent.Touched:Connect(function(hit)
	local h = hit.Parent:findFirstChild("Humanoid")
	if h ~= nil then
		local player = game.Players:GetPlayerFromCharacter(h.Parent)
		if player then
			RemoteEvents.Kick.OnServerEvent:Connect(function()
				player:Kick("You've been kicked!")
				print("Player kicked.")
			end)
		end
	end
end)

This is in a local script, and the RemoteEvent is fired from the client’s UI button.

I have the same setup for a player to be respawned, but the solution here should work the same.

Any assistance would be greatly appreciated!

Each time someone touches the part you are creating a connection for that player but not disconnecting it. A better way would be to only have one connection for the remote event and when its fired get each player that’s touching the platform

You’re creating a new connection every time someone steps on that platform, and it’s never disconnected which causes it to fire even when another player steps on.

Fixed code:

--//Services
local Players = game:GetService("Players")

--//Variables
local Part = script.Parent

--//Tables
local playersTouching = {}

--//Functions
Part.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	
	if not player or table.find(playersTouching, player) then
		return
	end
	
	table.insert(playersTouching, player)
end)

Part.TouchEnded:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	
	if not player then
		return
	end
	
	local playerIndex = table.find(playersTouching, player)
	
	if not playerIndex then
		return
	end
	
	table.remove(playersTouching, playerIndex)
end)

RemoteEvents.Kick.OnServerEvent:Connect(function()
	for i, player in ipairs(playersTouching) do
		player:Kick("You've been kicked!")
	end
	
	print("Players kicked.")
end)

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