Script that give players specific items upon spawning based on their Team property

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")

local function getTeamItems(team)
    local t4ble = {}
    
    for a, t in pairs(team:GetChildren()) do
        if t:IsA("Tool") then
            table.insert(t4ble, t)
        end
    end
    return t4ble
end

Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        if player.Neutral or not player.Team then
            return
        end
        local success, teamitems = pcall(getTeamItems, player.Team)
        
        if not success then
            warn("Failed to get team items: " .. teamitems)
            player:LoadCharacter()
            return
        end
        for u, y in pairs(teamitems) do
            y:Clone().Parent = player:FindFirstChildWhichIsA("Backpack")
        end
    end)
end)

Is this good for performance and are there things I can improve?

3 Likes

That script is about as efficient as could be for what you trying to do. You shouldn’t need to change it.

I’ve decided to come up with a better Script after a bit of thinking.

This Script clears a player’s StarterGear once their Team property changes and, if the player’s still under a Team after the change, fills the StarterGear up with the items for that Team. So yes, it could be improved. I hope this helps someone else out in the future. My topic has been solved.

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")

local function getTeamItems(team)
    local t4ble = {}
    
    for a, t in pairs(team:GetChildren()) do
        if t:IsA("Tool") then
            table.insert(t4ble, t)
        end
    end
    return t4ble
end

Players.PlayerAdded:Connect(function(player)
    local StarterGear = player:WaitForChild("StarterGear", 5)
    
    if not StarterGear then
        player:Kick("StarterGear not found!")
        return
    end
    if player.Team and not player.Neutral then
        for t, y in pairs(getTeamItems(player.Team)) do
            y:Clone().Parent = StarterGear
        end
    end
    player:GetPropertyChangedSignal("Team"):Connect(function()
        StarterGear:ClearAllChildren()
        if player.Neutral and not player.Team then
            return
        end
        for p, o in pairs(getTeamItems(player.Team)) do
            o:Clone().Parent = StarterGear
        end
    end)
end)
1 Like