How Do I fix this error while unequipping the gun while reloading?

So I made this gun where you can reload it and it connects to a GUI that shows the ammo amount but if I click to reload then unequip the gun it gives an error and doesn’t change the GUI and ammo amount and I get this error:

Players.ForgottenDogYT.Backpack.Ak 47.Server:85: attempt to index nil with ‘PlayerGui’

this is the code where it errors. also, this is a server script:

local function reload()
	if reloading then return end
	ReloadValue.Value = true
	ReloadTrack = script.Parent.Parent.Humanoid:LoadAnimation(ReloadAnim)
	CanFire = false
	reloading = true
	Player = game:GetService("Players"):GetPlayerFromCharacter(Tool.Parent)
	AmountGui = Player.PlayerGui:FindFirstChild("AmmoGui")
	AmountGui.AmmoFrame.AmmoAmount.Text = 40
	AmmoValue.Value = 40
	Ammo = 40
	reloading = false
	CanFire = true
	ReloadValue.Value = false

how can I make the GetPlayerFromCharacter(tool) also get it from the backpack? I’ve tried disabling the core GUI for backpacks but if i pick up a tool it also overrides the reload and breaks.

1 Like

Try this:

if not Player then Player = script.Parent.Parent end

Since the tool would be parented to the backpack, and the backpack is a child of the Player.

1 Like

do I put this before If not reloading?

Put it in front of the Player variable, since it’s checking if the player doesn’t exist.

I did that but then i got this error after unequipping it in the middle of reloading:

PlayerGui is not a valid member of Backpack “Players.ForgottenDogYT.Backpack”

My bad, try this:

if not Player then Player = script.Parent.Parent.Parent end
1 Like

It doesn’t error and it works!

1 Like