I'm currently trying to code a game after learning the basics of Roblox Studio and Lua, I made this script with my current knowledge. It's supposed to check if a player is in Team 1 and if they are, they will receive an item, but when I run the script, nothing happens.
I've tried moving it into different services, local script and Instance.new to directly create a tool, but nothing worked, so I assumed the problem is just the code
local players = game.Players
local team1 = game.Teams["Team 1"]
local team2 = game.Teams["Team 2"]
local tool = game.Workspace:WaitForChild("Tool")
local function starteritem(player)
if player and player.Team and player.Team == team1 then
local backpack = player:WaitForChild("Backpack")
local toolcopy = tool:Clone()
tool.Parent = backpack
end
end
for _, player in ipairs(players:GetPlayers()) do
starteritem(player)
end
I've tried moving it into different services, local script and Instance.new to directly create a tool, but nothing worked, so I assumed the problem is just the code. Currently the script is in a normal script and in the ServerScriptService.
You've got a timing issue. Let's talk about the flow of events when a game starts :
So your code is in a Script in ServerScriptService. It fires as soon as the game launches, and it says, "Please give all players in the game this item". Your script does exactly that, it loops over all zero players and calls it good.
So rather than telling players to get their items, make item gifting the responsibility of the Team object itself. Teams have a PlayerAdded event that will fire when a player joins and is added to the roster :
local Teams = game:GetService("Teams")
-- create a table that lists items to give players on each team
local TEAM_ITEMS = {
-- each team has their own list of things
Teams["Team 1"] = {
game.Workspace:WaitForChild("Tool"),
},
-- give Team 2 NOTHING!
Teams["Team 2"] = { }
}
local function givePlayerTeamItems(player, team)
-- escape if the listed team doesn't have any items defined
if not TEAM_ITEMS[team] then
warn(string.format("%s doesn't have an entry in the TEAM_ITEMS table", team.Name))
return
end
-- copy all the items into the player's backback
local tools = TEAM_ITEMS[team]
local backpack = player:WaitForChild("Backpack")
for _, tool in ipairs(tools) do
local toolCopy = tool:Clone()
toolCopy.Parent = backpack
end
end
-- loop over all of the teams and hook up a function that gives players their
-- specific items when they join the team
for _, team in ipairs(Teams:GetChildren()) do
team.PlayerAdded:Connect(function(player)
givePlayerTeamItems(player, team)
end)
end