Tool not parenting to player's backpack

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)

Here’s the output:
image

Would appreciate any help I could get!

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)
1 Like

Still doesn’t work, same output

1 Like

You need to add print statements for this purpose to pinpoint the issue

I did, my current code has print statements. You can check the output above, and it shows the exact line pretty much where the error is.

1 Like

Referencing the backpack in CharacterAdded fixed this for me :slight_smile:

2 Likes

This worked, thanks so much for your help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.