KeyCode Problem

So I am working on a my first gun. It’s not done but it works almost completely. The problem is the reloading part. I need to sense when a player presses R so I can start the reload part. The issue is that(after some debugging) shows that when I press any thing(including R) it prints out Enum.KeyCode.Unknown

Here is my local script so far:
local shootEvent = script.Parent:WaitForChild(“Shoot”)

local UIS = game:GetService("UserInputService")

local sound = script.Parent:WaitForChild("Shoot")

local plr = game.Players.LocalPlayer

local plrGui = plr.PlayerGui

local mouse = plr:GetMouse()

local gun = script.Parent

local gunGui = script.Parent.GunGui

local ammoCounter = gunGui.TextLabel

-- Settings

local maxAmmo = 10

local fullyAutomatic = false

local shootTimeCooldown = 0.1

local reloadTime = 2

-- INTERNAL VARIABLES FOR GUN

local shooting = false

local reloading = false

local ammo = maxAmmo

-----------------------------
function fireGun()
	ammo = ammo - 1
	ammoCounter.Text = tostring(ammo).."/"..tostring(maxAmmo)
	print("gun fired")
end

ammoCounter.Text = tostring(maxAmmo).."/"..tostring(maxAmmo)

gunGui.Parent = plrGui

gun.Equipped:Connect(function()
	gunGui.Enabled = true
	plr.CameraMode = Enum.CameraMode.LockFirstPerson
end)

gun.Unequipped:Connect(function()
	gunGui.Enabled = false
	plr.CameraMode = Enum.CameraMode.Classic
	shooting = false
end)
gun.Activated:Connect(function()
	-- Mouse click while gun equiped
	if not reloading and ammo > 0 then
		shooting = true
	end
end)

gun.Deactivated:Connect(function()
	-- Mouse release while gun equiped
	if fullyAutomatic then
		shooting = false
	end
end)

UIS.InputChanged:Connect(function(key)
	print(key.KeyCode)
	if key.KeyCode == Enum.KeyCode.R then
		print("attempted reload")
		if not shooting and ammo ~= maxAmmo and not reloading then
			reloading = true
			print("reload")
		end
	end
end)

coroutine.resume(coroutine.create(function()
	while wait() do
		if reloading and not shooting then
			wait(reloadTime)
			ammo = maxAmmo
			reloading = false
		end
	end
end))

while wait() do
	if fullyAutomatic then
		-- Handle things like the gun is fully automatic.
		while shooting and ammo > 0 and not reloading do
			fireGun()
			wait(shootTimeCooldown)
		end
	else
		-- Handle things like the gun is semi-automatic.
		if shooting then
			fireGun()
			wait(shootTimeCooldown)
			shooting = false
		end
	end
end
1 Like

I think it was a typo. You wrote UIS.InputChanged when you should’ve written UIS.InputBegan. If not, let me know.

Use InputBegan.

UIS.InputBegan:Connect(function(key, gp)
	if gp then return end -- stop the function if it's being processed by the game (chatting for example)

	if key.KeyCode == Enum.KeyCode.R then
		print("attempted reload")
		if not shooting and ammo ~= maxAmmo and not reloading then
			reloading = true
			print("reload")
		end
	end
end)

Alternatively, you can use ContextActionService.

1 Like