Ad
Log in to vote
0

How can I make a tool be equipped by holding down a key?

Asked by 5 months ago

Hello! I was wondering how I could make a tool be equipped by holding down a key and unequipped by letting go of it.

I'm assuming to make the holding down part to use UserInputService But I can't think of a way to make the tool equip and unequip by doing this.

Thanks!

1 answer

Log in to vote
0
Answered by 5 months ago
-- Vars: General
local player = game.Players.LocalPlayer
local character = player.Character

if not character or not character.Parent then -- It attempted to index nil, so I added this to check
    character = player.CharacterAdded:Wait()
end

local humanoid = character:FindFirstChildOfClass("Humanoid")

-- Vars: Input
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local desiredKey = Enum.KeyCode.E

local function keyIsDown() -- Returns if the key is down or not
    return UserInputService:IsKeyDown(desiredKey)
end

-- Vars: Tool
local tool = player.Backpack:WaitForChild("HoldTool") -- Replace with tool name
local handle = tool.Handle

local isHeld = false;

-- Functions

local function equipTool()
    if keyIsDown() then
        if isHeld == false then
            humanoid:EquipTool(tool)
        else if isHeld == true then 
                return
            end
        end
    else
        humanoid:UnequipTools()
    end
end

RunService.Heartbeat:Connect(equipTool)


I have no idea if this is the most optimal, but it works for me. It uses a combination of RunService and UserInput.

Every heartbeat, it checks if the key is down, and if it is, equip it. I did a check if it was held in fear that it might look weird if you kept equipping the tool over and over again.

0
Oops: I forgot! The script runs in StarterCharacterScripts SparkyTheCorruptCone 35 — 5mo
Ad

Answer this question