Backpack.Parent is nil

I don’t know how to explain further.

I have a variable wich is player:WaitForChild(“Backpack”) and when i print its parent, it says nil.
I simply don’t know why and i cannot figure it out.

Here is part of the script.

local GunModule = {}

--Folders & Services

local  ReplicatedStorage = game:GetService("ReplicatedStorage")
local GunsFolder = ReplicatedStorage.Guns

--Player stuff

local Player = game.Players.LocalPlayer
local PlayerBackpack = Player:WaitForChild("Backpack")



function GunModule.NewGun()
	local NewGun = {}
	setmetatable(NewGun, {__index = NewGun})
	
	
	local NewGunTool = GunsFolder.StarterGun:Clone()
	NewGunTool.Parent = PlayerBackpack
	
	
	NewGun.GunTool = NewGunTool
	NewGun.FireWait = .1
	NewGun.InitialDamage = 10
	NewGun.Range = 100
	NewGun.DamageLoseRatio = 0.5
	NewGun.GunType = "Auto"
	
	print(PlayerBackpack:GetChildren())

end
1 Like

Is this a Script or a LocalScript? LocalPlayer can only be referenced in LocalScripts and will return nil when you try to reference it in a server-sided script, which would explain your issue here.

The script specifies it’s a ModuleScript. The question is if the Script requiring the Module is server or client sided.

Once a character dies, the Backpack is removed and a new one will be created – populating it with the contents of StarterPack and StarterGear.

(Backpack Docs)

If you want to get the backpack after the player dies you need to get the new one in the player (either change the variable when the player dies or always get the new one when the code needs the backpack).

I believe the problem is that you don’t have connections to clean up your new gun object when the humanoid dies. If your gun object is destroyed then it won’t try to access the destroyed Backpack.

This also probably prevents a memory leak where the Backpack is never garbage collected because your new gun object references it.

Wait for the character to load first before checking if the backpack is there. When the character loads, the backpack is reconstructed.

1 Like

So i kinda of forgot about this post, but i fixed everything. Turns out, after the backpack loads the first time, it loads again (why?) and that first backpack variable becomes nil. i fixed it by making the variable inside the GunModule.NewGun() function. Thank you for anyone who helped.

This is because the character loads. However, I’d prefer Roblox to not construct the backpack in the first place if the character is not loaded.

This is mainly to prevent tools from showing up in the backpack while the game is loading.

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