So, I want to know how do I add an item to all players when a map is selected, and removing the given item to the players when teleporting everyone back to the lobby.
I’ve maded this script when the players is on the specific map:
local players = game:GetService("Players")
local serverStorage = game:GetService("ServerStorage")
if chosenMap.Name == "My Map" then
for _, givePistol in pairs(players:GetPlayerFromCharacter()) do
serverStorage.Tools.Pistol:Clone().Parent = givePistol.Backpack
end
I’ve don’t made any script when teleporting players back to the lobby.
:GetPlayerFromCharacter() is not a function to get a dictionary, its a function to get the player from the character.
for example:
print(game.Players:GetPlayerFromCharacter(Character).Name)
expected output: Player’s name
So you should make the script this:
local players = game:GetService("Players")
local serverStorage = game:GetService("ServerStorage")
if chosenMap.Name == "My Map" then
for _, givePistol in pairs(players:GetPlayers()) do
serverStorage.Tools.Pistol:Clone().Parent = givePistol.Backpack
end
end
for _, removePistol in pairs(players:GetPlayers()) do
if removePistol.Backpack.Pistol.Name == "Pistol" then
removePistol.Backpack.Pistol:Destroy()
end
end
for _, removePistol in pairs(players:GetPlayers()) do
local pistol = removePistol.Backpack:FindFirstChild("Pistol")
if pistol then
if string.match(pistol.Name, "Pistol") then
removePistol.Backpack.Pistol:Destroy()
else
warn("PISTOL IS NOT NAMED PISTOL, CURRENT NAME: " .. tostring(pistol.Name))
end
else
warn("PISTOL DOESNT EXIST OR IS NIL")
end
end
for _, removePistol in pairs(players:GetPlayers()) do
removePistol.Backpack:ClearAllChildren()
if player.Character:FindFirstChildOfClass("Tool") then
player.Character:FindFirstChildOfClass("Tool"):Destroy()
end
end
end
for _, removePistol in pairs(players:GetPlayers()) do
if removePistol.Backpack:FindFirstChild("Pistol") then
removePistol.Backpack.Pistol:Destroy()
end
end
When the pistol is equipped it is parented to the player’s character. You can just destroy it from there.
You can check if the character exists and if they have a pistol.
Updated code with improvements:
for _, removePistol in pairs(players:GetPlayers()) do
if removePistol.Character ~= nil then
local character = removePistol.Character
local Backpack = removePistol.Backpack
local Pistol = character:FindFirstChild("Pistol") or Backpack:FindFirstChild("Pistol")
if Pistol then
Pistol:Destroy()
end
end
end