So this script is supposed to fire when a player has equipped the tool, and clicked r. But I just get an error message saying Attempt to call a nil value.
It also gives me the error message when I click r without the tool equipped, meaning that portion of the script also doesn’t work. What should I do differently. The script is local and located in side the tool.
function rreload ()
function onKeyPress(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.R then
print("Hi")
end
end
end
game:GetService("UserInputService").InputBegan:connect(onKeyPress)
tool.Equipped:Connect(rreload)
Ok ye I changed it and it seems to be working now. Thanks.
Also real quick after I click r and un equip the tool, it will work without the tool equipped.
function rreload ()
game:GetService("UserInputService").InputBegan:connect(onKeyPress)
end
tool.Equipped:Connect(rreload)
function onKeyPress(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.R then
print("Hi")
end
end
I’m guessing you want to listen to the R key being pressed down only when the tool is equipped. To do something like this you’d need to do something like this:
local UserInputService = game:GetService("UserInputService")
local tool = script.Parent
local isEquipped = false
tool.Equipped:Connect(function()
isEquipped = true
end)
tool.Unequipped:Connect(function()
isEquipped = false
end)
UserInputService.InputBegan:Connect(function(inputObject, gameProcessedEvent)
if not isEquipped then
return
end
if inputObject.KeyCode == Enum.KeyCode.R then
print("Tool is equipped and R was pressed!")
end
end)
You could also do something like this:
local UserInputService = game:GetService("UserInputService")
local function isToolEquipped()
local tool = script.Parent
return if tool.Parent then tool.Parent:FindFirstChildOfClass("Humanoid")~=nil else false
end
UserInputService.InputBegan:Connect(function(inputObject, gameProcessedEvent)
if not isToolEquipped() then
return
end
if inputObject.KeyCode == Enum.KeyCode.R then
print("Tool is equipped and R was pressed!")
end
end)
Basically when InputBegan is fired, all you need to do is check if the tool is equipped. If it isn’t equipped, then you can ignore the input by stopping the function with return.