UserInput Spamming nil?

Im trying to make a Gun script. However i need to get the UserInputService if the player reloads his Gun with R. I dont know why but after using the Gun for a bit, the UserInputService starts to print nil and not like once it doubles everytime i left click. This makes my studio lag really bad (1million nils starting a function would crash any studio i guess) its obviously the first time im making a Gun Script and its not done yet. my current script is:

local MaxAmmo = 7
local Ammo = MaxAmmo
local Damage = 25
local HeadShot = 50
local Reloading = false
local UIS = game:GetService("UserInputService")
local rs = game:GetService("ReplicatedStorage")
local cooldown = 1
local canshoot = true

script.Parent.Equipped:Connect(function(Mouse)
	local function reload(key)
		print(key)
		if key ~= nil then
			if key.KeyCode == Enum.KeyCode.R then
				if Ammo ~= MaxAmmo then
					if Reloading == false then
						print("reload started")
						Reloading = true
						wait(3)
						Ammo = MaxAmmo
						Reloading = false
					end
				end
			end
		end
		
		script.Parent.Activated:Connect(function()
			if Ammo > 0 and not Reloading then
				if canshoot == true then
					canshoot = false
					Reloading = true
					Ammo = Ammo - 1
					local shot = rs.Shot:Clone()
					shot:GetChildren().Cframe = script.Parent.Handle.CFrame
					shot.Parent = game.Workspace
					
					wait(cooldown)
					shot:Destroy()
					Reloading = false
					canshoot = true
				end
			elseif Ammo == 0 and not Reloading then
				Reloading = false
				reload()
			else
				Reloading = false
			end
		end)
	end
	UIS.InputBegan:Connect(reload)
end)

heres the output after a few clicks:

2021-04-04
i hope its nothing to big and im missing something but ive been looking for a solution for about 3 days now. i also take any help for the Gun itself if i did something unnecessary. This is also my first Topic so dont hate on me if i did something wrong please. >-<

Thanks for the help,
beast_quest3

1 Like

I think it’s because everytime you equip the tool, you connect a function to InputBegan. So let’s say you equip the tool 5 times. InputBegan will fire 5 times everytime you start an input since you started an event listener everytime you equip the tool. So if you equip it like 20 times, everytime you start an input (and there are A LOT trust me), it prints something 20 times since you did print(key).

1 Like

I dont think it can be because of the .Equipped function, because it still prints the other inputs only once its only printing nil alot thats what is confusing me a lot. I mean how can an UserInput be nil?

in case there is still something wrong with the .Equipped function how would i get around that without the player being able to shoot without the Gun in his hand?

edit: i found out it prints nil when Ammo is empty i can fix it now thanks

1 Like