Help with ammo Box script

So I’m making a gun script for my game and I came to the part of the ammunition,everything works perfectly but what I’m having trouble with is the ammo box,which is an Item that on touch disappears and gives the player 30 bullets on the inventory.
When I test the script and touch a ammo box I get the 30 bullets,however when I spawn another one and I touch it it does’nt work anymore,I know that this is because the script only detects the ammo box once,I used a while loop so the ammo box variables always updates but the problem still remains.
Is there a way to fix this?.

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
local M1911A1  = script.Parent
local debounce = false
local hum = player.Character.Humanoid
--------------------------------
local MousePosition = Mouse.Hit.Position
local BT = game.ReplicatedStorage.BulletTrail
local char = player.Character
-----------------------------------------------Ignore dis
local MouseIcon = true
UIS.InputBegan:Connect(function(inp, p)
	if inp.UserInputType == Enum.UserInputType.MouseButton2 and MouseIcon == true then
		MouseIcon = false
	elseif inp.UserInputType == Enum.UserInputType.MouseButton2 and MouseIcon == false or inp.UserInputType == Enum.UserInputType.MouseButton1 and MouseIcon == false then
		MouseIcon = true
	end
end)
---------------------------------------Animations
local Animation1 = M1911A1.EmptyReload
local Animation2 = M1911A1.GunReload
local Animation3 = M1911A1.Shooting
--------------------------------
local EmptyRl = hum:LoadAnimation(Animation1)
local Reload = hum:LoadAnimation(Animation2)
local Soot = hum:LoadAnimation(Animation3)
-------------------------------------------Ammunition variables
local EmptyAmmo = 7
local ammo = 7
local maxammo = 8
local reloading = false
local Inventoryammo = 0
local MaxInventoryAmmo = 200
local ammotosubtract = 0
local ammoboxcooldown = true
local waitiningforammobox = true
---------------------------------------------------------reloading function--------------------------------------------------------------
local function reload()
	if reloading == false and ammo == 0 and player.Character.Humanoid.WalkSpeed == 16 and M1911A1.Equipped and MouseIcon == true and Inventoryammo > 0 then
		reloading = true
		M1911A1.SoundEffects["M1911 Reload"]:Play()
		M1911A1.SoundEffects["M1911 Reload"].Volume = 0.4
		EmptyRl:Play()
		task.wait(1.7)
		ammo = EmptyAmmo
		Inventoryammo -= 7
		player.PlayerGui.Ammo.AmmoBackGround.AmmoCount.Text = ammo.."/"..Inventoryammo
		reloading = false
	elseif reloading == false and ammo > 0 and ammo < 8 and player.Character.Humanoid.WalkSpeed == 16 and M1911A1.Equipped and MouseIcon == true and Inventoryammo > 0 then
			reloading = true
			M1911A1.SoundEffects["pistol_reload1"]:Play()
		M1911A1.SoundEffects["pistol_reload1"].Volume = 0.3
			Reload:Play()
			task.wait(1.2)
	        ammotosubtract = maxammo - ammo
			Inventoryammo -= ammotosubtract
			ammo = maxammo
		    player.PlayerGui.Ammo.AmmoBackGround.AmmoCount.Text = ammo.."/"..Inventoryammo
			reloading = false
		end
end


--------------------------------------------------------Shooting function----------------------------------------------------------------
M1911A1.Activated:Connect(function()
	if debounce == false and ammo > 0 and reloading == false and MouseIcon == true and hum.WalkSpeed == 16 then
		debounce = true
		ammo -= 1
		-------------------------------------------------------------------------------------------------------	
		M1911A1.Shoot:FireServer(Mouse.Hit.Position)
		M1911A1.SoundEffects["M1911 Gunshot"]:Play()
		M1911A1.SoundEffects["M1911 Gunshot"].Volume = 0.5
		Soot:Play()
		player.PlayerGui.Ammo.AmmoBackGround.AmmoCount.Text = ammo.."/"..Inventoryammo
		task.wait(0.2)
		debounce = false
	elseif debounce == false and ammo == 0 and reloading == false and MouseIcon == true and hum.WalkSpeed == 16 then
		M1911A1.SoundEffects["clip_empty"]:Play()
		M1911A1.SoundEffects["clip_empty"].Volume = 0.5
	end	
end)

-----------------------------------------------------Reloading Key
UIS.InputBegan:Connect(function(inputObject, isTyping)
	if isTyping then return end
	if inputObject.KeyCode == Enum.KeyCode.R then
		reload()
	end	
end)
------------------------------------------------Dis is where the problem is at-----------------------------------------------------------
while true do
	wait(2)
if waitiningforammobox == true then
	local AmmoBox = game.workspace:FindFirstChild("AmmoBox") or game.workspace:WaitForChild("AmmoBox")
	local BoxLowerPart = AmmoBox:FindFirstChild("Lower") or AmmoBox:WaitForChild("Lower")
waitiningforammobox = false

------------------------------------------------Make the ammo box give ammo on touch function--------------------------------------------

BoxLowerPart.Touched:Connect(function()
	if ammoboxcooldown == true then
	ammoboxcooldown = false
	AmmoBox:Destroy()
	Inventoryammo += 30
	if M1911A1.Equipped then
	player.PlayerGui.Ammo.AmmoBackGround.AmmoCount.Text = ammo.."/"..Inventoryammo
	end
	end
	ammoboxcooldown = true
	waitiningforammobox = true
end)
end
end

Can you please clarify about what you wanna do?

1 Like

Alternatively to have a more organized system you could mitigate your script into the AmmoBox alone and turn the inventoryammo variable into an external variable that other scripts can access.

I can‘t really comprehend what the BoxLowerPart and all the cooldowns are trying to achieve.

1 Like

I’ll try to do that.
Also the boxlowerpart is just a part of the ammobox model,the ammoboxcooldown is a boolean made so you don’t receive 3 times the intended ammo,thewaitingforammobox was just a boolean that I used to try to fix my problem.

Well uh,have you seen arsenal?,well when you kill enemies they drop two items,one that heals you and another that gives ammunition.I’m basically trying to do something like that.
The ammo box is the item that will give you ammo and the script from above is the whole gun script

There is a cooldown for player to get another ammo box also?

It was just an attempt to fix the error,the purpose of the boolean was just to search or wait for another ammo box each time one gets consumed but did’nt seemed to work

Do you want to make it so that player gets ammo everytime they touch an ammo box? Can you show me the code that you used to spawn the new ammo boxes?

yes
(additional words because mmy post needs more characters)

Can you show me the code that you used to spawn the new ammo boxes?

local AmmoB = game.ReplicatedStorage.AmmoBox

local function clone()
	local Cl = AmmoB:Clone()
	Cl.Name = "AmmoBox"
	Cl.Parent = game.Workspace
	Cl.Lower.Position = Vector3.new(math.random(-10,10),0,math.random(-10,10))
end
clone()
wait(6)
clone()
wait(6)
clone()

Maybe instead of detecting Touched event from your gun script, you can put it inside your spawning script

So I’ll just use a remote function to connect both scripts?

wait, one is local script and another is server script? isn’t putting the inventory ammo inside a local script will cause exploiters to be able to change how much inventory ammo they have?

yes the gun script is a local one.
However I dont care too much about hacker changing the ammo as the game I’m making will be singleplayer (The enemies will be IA)

hmmmm, yea you can use a remote event

Alright,I’m going to check it out.

Something like this:

-- Your Server Script
local AmmoB = game.ReplicatedStorage.AmmoBox

local plrCollectAmmoRemoteEvent -- your remote event for collecting ammo

local function clone()
	local Cl = AmmoB:Clone()
	Cl.Name = "AmmoBox"
	Cl.Parent = game.Workspace
	Cl.Lower.Position = Vector3.new(math.random(-10,10),0,math.random(-10,10))

	local alreadyTouched = false -- to only allow to touch one time
	Cl.Lower.Touched:Connect(function(hitPart)
		if alreadyTouched then return end
		
		local model = hitPart:FindFirstAncestorOfClass("Model")
		if model then
			local plr = game:GetService("Players"):GetPlayerFromCharacter(model)
			if plr then
				alreadyTouched = true
				Cl:Destroy()
				plrCollectAmmoRemoteEvent:FireClient(plr)
			end
		end
	end)
end
clone()
wait(6)
clone()
wait(6)
clone()

and

-- Put inside your gun script
local plrCollectAmmoRemoteEvent -- your remote event for collecting ammo

plrCollectAmmoRemoteEvent.OnClientEvent:Connect(function()
	inventoryAmmo += 30
	print(inventoryAmmo) -- check to see if it works
	-- other stuffs that you want to do...
end)

Ammo Box Work.rbxl (55.4 KB)
here is a demo file

Thanks! it finally worked
Also sorry for answering late I did a script on my own but it was’nt that good.