Touch part that add players to a table?

How would I make a part that when touched, it gets the player and adds them to a table and before doing that it checks if the number of players in the table is greater than or equal to x? How would I do this?

Just used a Touched event to detect when it happens, pull the player name and use table.insert to add it to the table. Before doing this, just use the “#” operator to find the table length then compare it to x.

how would i exactly pull the players name though?

-- example
BasePart.Touched:Connect(function(hit) -- the object that hit it
   local plr = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent) -- get the player's character

   if plr then -- check if it was a player
       -- object belongs to a player, do stuff
       print(plr.Name) --> prints whoever the player was
   end
end)

Just do it like this

local table = {}

local function addPlayerToTable(player)
   local name = player.Name
   table.insert(table, name)
   if #table > x then
      --- do operations here  
   else
      ---whatever else
   end
end)

part.Touched:Connect(addPlayerToTable)
4 Likes