Hey there, I’ve been trying for quite a bit and have been using multiple methods to achieve this but nothing seems to work.
Basically, I’m making a gun RNG game, and I’m trying to have it so that when a player rolls a specific weapon, it gets put in their backpack. However, it just isn’t working for whatever reason.
Code:
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ToolsFolder = ReplicatedStorage:WaitForChild("Weapons")
Players.PlayerAdded:Connect(function(Player)
local Weapons = Player:WaitForChild("Weapons")
local Backpack = Player:WaitForChild("Backpack")
Player.CharacterAdded:Connect(function(_)
Weapons.ChildAdded:Connect(function(Child)
print("Child added!")
local WeaponName = Child.Value
for _, v in pairs(Backpack:GetChildren()) do
if v.Name == WeaponName then
print("Destroying...")
Child:Destroy()
break
end
end
local WeaponTool = ToolsFolder:WaitForChild(WeaponName):Clone()
print(WeaponTool.Name)
WeaponTool.Parent = Backpack
print("Gave them the tool!")
end)
end)
end)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ToolsFolder = ReplicatedStorage:WaitForChild("Weapons")
Players.PlayerAdded:Connect(function(Player)
local Weapons = Player:FindFirstChild("Weapons")
local Backpack = Player:FindFirstChild("Backpack")
if not Weapons then
Weapons = Instance.new("Folder")
Weapons.Name = "Weapons"
Weapons.Parent = Player
end
if not Backpack then
Backpack = Instance.new("Backpack")
Backpack.Name = "Backpack"
Backpack.Parent = Player
end
Player.CharacterAdded:Connect(function(_)
Weapons.ChildAdded:Connect(function(Child)
print("Child added!")
local WeaponName = Child.Value
if not WeaponName then
warn("Weapon name is missing!")
return
end
-- Check if weapon already exists in the backpack
for _, v in pairs(Backpack:GetChildren()) do
if v.Name == WeaponName then
print("Destroying...")
Child:Destroy()
return
end
end
-- Clone and move the weapon to the backpack
local WeaponTool = ToolsFolder:FindFirstChild(WeaponName)
if WeaponTool then
local ClonedTool = WeaponTool:Clone()
ClonedTool.Parent = Backpack
print("Gave them the tool!")
else
warn("Weapon not found in ToolsFolder!")
end
end)
end)
end)