I have a script that I want that when the player enters a Team I gave him a Weapon but if the player changes his team I want him to only have the weapon that will be granted when he enters the Team .... What I did in the script is that when the player enters the Team I gave him a Weapon but at the same time I eliminated the player's Backpack, okay I try the script and everything is fine but my problem with that script is that when the player's Backpack is removed the weapon appears that is granted when entering the Team but as Arma [2]. So I went to a Team and they gave me the weapon, then I changed Team and they gave me the other Team's weapon and they eliminated the Weapon I had, okay then it is supposed that the first weapon entered into my 'Backpack' is the one that gives me the first Team I joined; When I enter the other Team, they give me the weapon they give me as a secondary. I hope you understand me Thanks for reading!
It is a Normal Script and it is located in the Workspace .
01 | print ( "hola" ) |
02 | local teams = game:GetService( "Teams" ) |
03 | local Team 1 = game.Teams.Police |
04 | local Team 2 = game.Teams.Criminal |
05 | local Tools 1 = game.ReplicatedStorage.PoliceTools |
06 | local Tools 2 = game.ReplicatedStorage.CriminalTools |
07 |
08 | function Tools() |
09 | for _,v in pairs (Tools 1 :GetChildren()) do |
10 | v:Clone().Parent = Team 1 |
11 | end |
12 | for _,v in pairs (Tools 2 :GetChildren()) do |
13 | v:Clone().Parent = Team 2 |
14 | end |
15 | end Tools() |
You are on the right track, however the reason your code may not work as expected, is because you are removing the tools at the same time as adding new ones.
To fix this, before adding tools use player.Backpack:ClearAllChildren()
in order to get rid of any existing tools.
Also, in order to clean your code a bit, you can create a single function which handles iterating through a given container and copying the children to the player's backpack. In my snippet below, that is AddTools
.
After clearing the children, check which team the player has been added to, and call AddTools
to give them the appropriate gear.
01 | local teams = game:GetService( "Teams" ) |
02 | local Team 1 = game.Teams.Police |
03 | local Team 2 = game.Teams.Criminal |
04 | local Tools 1 = game.ReplicatedStorage.PoliceTools |
05 | local Tools 2 = game.ReplicatedStorage.CriminalTools |
06 |
07 | local function AddTools(backpack, tools) |
08 | for _, tool in pairs (tools) do |
09 | tool:Clone().Parent = backpack |
10 | end |
11 | end |
12 |
13 | local function ChangeTeam(player) |
14 | local backpack = player.Backpack |
15 | backpack:ClearAllChildren() |
Let me know if you have any questions or if you try this and it doesn't work as expected.
In line 43, you’re using LocalPlayer
which is nil
on the server.
And on lines 23 and 34, it should be :Destroy()
, not :Remove()
.