Ammo give/take script not working

So, my script to be able to take ammo and place it doesn’t work, it gives an error ‘Ammo is not a valid member of Backpack’, so you can’t take ammo if you have none in your backpack, but you can still add it if you have the tool.

local ClickDet = Instance.new("ClickDetector")
ClickDet.Parent = script.Parent.AmmoStorager
local AmmoTool = game.ServerStorage["Ammo"]
local AmmoCount = Instance.new("IntValue")
AmmoCount.Parent = script.Parent
AmmoCount.Value = 0

ClickDet.MouseClick:Connect(function(player)
	if player.Backpack["Ammo"] then
		AmmoCount.Value = AmmoCount.Value + 1
		player.Backpack["Ammo"]:Destroy()
		print(AmmoCount.Value)
	elseif not player.Backpack["Ammo"] then
		if AmmoCount.Value <= 0 then
			wait()
		else
			local give = AmmoTool:Clone()
			give.Parent = player.Backpack
			script.Parent:Destroy()
			AmmoCount.Value = AmmoCount.Value - 1
		end
	end
end)

Any help would be appreciated.

2 Likes

It would help if you could provide more context to this question. For example,

  • What exactly do you want the script to do?
  • Could you provide more information on the error (such as which line is throwing the error)?
  • Have you tried print tracing to see exactly which branches of code are being executed?

This way other developers will be better placed to answer any queries / launch investigations into why your code isn’t behaving as expected.

Thanks, -Tom :slight_smile:

The error is at line 9. Want it to:

Take ammo if the value is over 0 and you have none in your backpack.
Place ammo in it if you have it in your backpack and increase the value.

Placing ammo works, just taking doesn’t.

I’d use FindFirstChild function to see if Ammo exists instead of square brackets.

2 Likes

Works perfectly. Thanks, I guess.