I have a despawn script. Models spawn with the player’s name in a folder. I have a loop where it will go through all of the active models and makes sure that the player is still in the server otherwise it will be destroyed, My problems is, I don’t know how to check everyone’s name then destroy it. This is my current script but it only checks 1 player than destroyed it.
local Players = game:GetService("Players")
local ShipSpawn = workspace:WaitForChild("ShipSpawns") -- Where models are stored
wait(15)
while wait(15) do
for _,ship in pairs(ShipSpawn:GetChildren()) do
for i, plr in pairs(Players:GetPlayers()) do
if ship.Name == Players[plr.Name] then
break
else
ship:Destroy()
end
end
end
end
local hasPlayer
for i, plr in pairs(Players:GetPlayers()) do
if ship.Name == Players[plr.Name] then
hasPlayer = true
end
end
if not hasPlayer then
ship:Destroy()
end
Something like this could work, because the function then gets to iterate through the entire player-list and see if the two names match.
If they do then the variable “hasPlayer” is changed, if not then the variable remains untouched, meaning that the comparison through the entire list was unsuccesful.
for _, Ship in pairs(ShipSpawn:GetChildren()) do
if not Players:FindFirstChild(Ship.Name) then
Ship:Destroy()
end
end
This is the most efficient way of doing it - however, more efficient than this would only be checking when a player leaves or joins via Event Connections, such as PlayerRemoving.
2. Break only on finding the ship
I wouldn’t recommend this, but you could do it like this:
for _,ship in pairs(ShipSpawn:GetChildren()) do
for i, plr in pairs(Players:GetPlayers()) do
if ship.Name == Players[plr.Name] then
ship:Destroy()
break
end
end
end
This is less efficient than #1 though, because you’re having to do additional Lua calls instead of letting the far better C-API method FindFirstChild do that for you.