I’m trying to make a part where a player touches and they will be added into a table. However, when I test my script using 2 players it appears that only 1 player can be in the table at a time. How do I add multiple players in a table?
Your myTable
variable is only accessible within your Touched
event function, so each time a player touches the part, a new table is assigned to your variable, and then immediately discarded after your print statement executes.
To store future players, just move your variable declaration for myTable into the global scope:
--//top of your script
local part = script.Parent
local myTable = {}
That’s because the table is defined locally, inside the touched event, which means it will reset every time a new player touches the part. Instead you must define it outside the function scope:
local myTable = {}
part.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent) --getting the actual player instance
if player and not table.find(myTable, player) then
table.insert(myTable, player)
print(myTable)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local index = table.find(myTable, player)
if index then
table.remove(myTable, index)
end
end)
In addition to what was mentioned in the previous posts, I would recommend checking if that player’s Character was already added to the table / if the Character hasn’t been added yet so that duplicates of the same Character are not continuously added whenever they activate the function:
if player and not table.find(myTable, player.Parent) then
table.insert(myTable, player.Parent)
end
Additionally, you’ll need to remove a character model instance from the table whenever the “CharacterRemoving” event is fired for that particular character model. A player’s character models will not be considered the same. As such it’s best to store player instances instead of the character model instances of player instances.
A couple of issues with this, you’re ignoring the player’s character’s equipped tools/worn accessories, you’re not checking if the player instance already exists within the table before inserting it into the table, which will result in the table containing duplicate values and you’re not removing the player instance from the table when that particular player instance leaves the game.
local players = game:GetService("Players")
local part = script.Parent
local touchedPlayers = {}
part.Touched:Connect(function(hit)
local hitModel = hit:FindFirstAncestorOfClass("Model")
if hitModel then
local hitPlayer = players:GetPlayerFromCharacter(hitModel)
if hitPlayer then
if not table.find(touchedPlayers, hitPlayer) then
table.insert(touchedPlayers, hitPlayer)
end
end
end
end)
players.PlayerRemoving:Connect(function(player)
local tablePlayer = table.find(touchedPlayers, player)
if tablePlayer then
table.remove(touchedPlayers, tablePlayer)
end
end)