How to Use UserInputService with a Tool?

  1. What do you want to achieve?
    I want to make it so when I press a different key, other than MouseButton1, there will be a different attack.

  2. What is the issue?
    The problem is, I can not achieve this because I am unsure of how to use UserInputService on a tool.

  3. What solutions have you tried so far?
    Every time I have tried, nothing has worked, and I have not found anything on the DevForum related to this.

For example:

UserInputService.InputBegan:Connect(function(Input, GPE)
	if Input.KeyCode == Enum.KeyCode.F then
		-- different attack code here
	end
end)

Right now, I am only using the Tool.Activated function for an attack.

local function Activated()
	if db == true then return end
	local Humanoid = script.Parent.Parent.Humanoid
	print("activated")
	db = true
	Swing1Track = Humanoid:LoadAnimation(Swing1)
	Swing1Track:Play()
	wait(0.3)
	Caster:Start()
	wait(1)
	Caster:Stop()
	wait(2)
	db = false
end

Sorry if this is unclear, I’m a little stumped on how to ask this question.
Thanks in advance.

1 Like

So basically, an input to activate a tool?

local Tool = script.Parent
local Equipped = false

function doSomething()
    -- runs when F is pressed
end

UIS.InputBegan:Connect(function(Input,GPE)
    if Input.KeyCode == Enum.KeyCode.F and not GPE and Equipped then doSomething() end
end)

Tool.Equipped:Connect(function()
    Equipped = true
end)

Tool.Unequipped:Connect(function() -- It might be UnEquipped, I'm not sure.
    Equipped = false
end)

Edit : You should move this to #help-and-feedback:scripting-support

dont use tools if your using UserInputService class, just set a string/bool/int value for determining the selected weapon, visualization should be attaching/welding a physical fake weapon to the character or viewmodel

Actual code for the weapon should be managed by a weapon manager of some sort

But honestly, this is roblox anyway if it works it works so idc rlly

1 Like

You can use ContextActionService for that as it is prepared for these kind of situations.
A simple example:

local ContextActionService = game:GetService("ContextActionService")
local AttackHotKey = Enum.KeyCode.F
local AttackAction = "DiffAttack"
local Tool = ToolLocation

local function OnDiffKeyPressed(ActionName: string, InputState: Enum.UserInputState)
	if InputState == Enum.UserInputState.Begin then
		--| Your Different Attack Code Here.
	end
end

Tool.Equipped:Connect(function()
	ContextActionService:BindAction(AttackAction, OnDiffKeyPressed, false, AttackHotKey)
end)

Tool.Unequipped:Connect(function()
	ContextActionService:UnbindAction(AttackAction)
end)

As you see, no need for input service here with its conditions…

3 Likes

Thank you so much for your help, this worked perfectly for me!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.