Want to know how I can add players to a table and remove when they are not touching

I am making a last player standing game. I want to make that if players are touching a part they will be added into a table and if they stop touching the part they will be removed from the table.

I don’t know how to script the second part and if I script the first part it adds a single player multiple times.

more context please :slight_smile: if possible

Try this:

local Players = game:GetService("Players")
local part = script.Parent

local playersOnPart = {}

part.Touched:Connect(function(otherPart)
    local character = otherPart.Parent
    local plr = Players:GetPlayerFromCharacter(character)
    if player then
        table.insert(playersOnPart, plr)
    end
end)

part.TouchEnded:Connect(function(otherPart)
    local character = otherPart.Parent
    local plr = Players:GetPlayerFromCharacter(character)
    if plr then
        for i, p in ipairs(playersOnPart) do
            if p == plr then
                table.remove(playersOnPart, i)
                break
            end
        end
    end
end)

Also you should present the script you’ve written first so we can help.

First part of the script you sent is working but the issue is that it is adding me multiple times

local Players = game:GetService("Players")
local part = script.Parent

local playersOnPart = {}

part.Touched:Connect(function(otherPart)
	local character = otherPart.Parent
	local plr = Players:GetPlayerFromCharacter(character)
	if plr then
		table.insert(playersOnPart, plr.Name)
		print(playersOnPart)
	end
end)

I changed your script, add now it adds the player name

Try adding a table.find() to see if the player is already on the part. It’s adding you multiple times because of your body parts moving, like this:

if table.find(playersOnPart, plr) then
	else
	table.insert(playersOnPart, plr)
end

Thanks, It worked. If I want to display the name of the player on a text label so I will do this

TextLabel.Text = plr.Humanoid.DisplayName

If your trying to show the display name then yes.

1 Like

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