Shotgun Reloading - ContextActionService Help

So currently I’m working on my shotgun and I’m having a problem with the player clicking the R key multiple times. I bind the R key to the player when they equip the weapon. My shotgun’s max ammo value is 3, is their a way I can limit the amount of times the player can click the R key.

– Here is the Problem with the Shotgun UI
– Which videogame is this from ?

Shotgun UI Ammo Problem

– I clicked the R Key 7 times now the Ammo has a Value of 21

– This is the Code I used

-- Local Script

-- This will reload when the Player clicks R and the Ammo is 0
function reload(actionName, inputState, inputObject)
	if actionName == ActionReload and inputState == Enum.UserInputState.Begin then
		if Ammo == 0 then
			print("You are Reloading")
			ShotgunReload:Play() 
			wait(2.8)
			Ammo = Ammo + 3
			updateUIR()
			updateText()
		end

	end
end
2 Likes

I’m having a hard time understanding what you mean, but do you want them not to be able to reload while already in a reload state? If so then use a debounce

local IsInReloadState;

function reload(actionName, inputState, inputObject)
	if actionName == ActionReload and inputState == Enum.UserInputState.Begin then
		if Ammo == 0 then
if(not IsInReloadState) then
            IsInReloadState = true;
			print("You are Reloading")
			ShotgunReload:Play() 
			wait(2.8)
			Ammo = Ammo + 3
			updateUIR()
			updateText()
            IsInReloadState = false;
end;
		end

	end
end

If this isn’t what you want, can you please explain a little more?

Use math.clamp to limit a number within a range.
Example:

local Ammo = 2
local MaxAmmo = 3
local MinAmmo = 0

local ContextActionService = game:GetService("ContextActionService")

local function onAction(Name, State, Input)
    if State == Enum.UserInputState.Begin and Name == "Reload" then
        -- do whatever
        Ammo = math.clamp(Ammo + 3, MinAmmo, MaxAmmo)
        -- returns 3 because the highest value that can return is 3
    end
end

ContextActionService:BindAction("Reload", onAction, false, Enum.KeyCode.R)
1 Like

So whenever the player clicks R they’re supposed to reload if their Ammo = 0. However, they’re able to click R multiple times instead of just once if their Ammo = 0 to reload.