Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

When i press the key nothing happens and there are no errors in the script, any help?

Asked by
Dec_ade 47
4 years ago
local UserInputService = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer

local CombatEnabled = false

UserInputService.InputBegan:Connect(function(Input,IsTyping)
    if not IsTyping then
        if Input.KeyCode == Enum.KeyCode.E then
            CombatEnabled = true
        end
    end
end)

spawn(function()
    while CombatEnabled == true do
        wait(0.1)
        print("Combat Enabled!")

        if CombatEnabled == false then
            print("Combat Disabled")
            break
        end
    end
end)

UserInputService.InputEnded:Connect(function(Input, IsTyping)
    if not IsTyping then
        if Input.KeyCode == Enum.KeyCode.E then
            CombatEnabled = false
        end
    end
end)

This local script is inside the starterpack, and there are no errors in the output.

1 answer

Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

Hello there.

Issue:

The while loop would immediately stop CobatEnabled would be false so the while loop wouldn't run.

Fix:

Use a while true do loop checking if combat is enabled.

Improvments:

  1. Don't use break on the while loop if the combat isn't enabled.

  2. Use coroutines instead of spawn as spawn has a built-in delay.

  3. Use game:GetService() with the Players service.

Fixed code:

local UserInputService = game:GetService("UserInputService")
local Player = game:GetService("Players").LocalPlayer

local CombatEnabled = false

UserInputService.InputBegan:Connect(function(Input,IsTyping)
    if not IsTyping then
        if Input.KeyCode == Enum.KeyCode.E then
            CombatEnabled = true
        end
    end
end)

coroutine.wrap(function()

    while true do
        if CombatEnabled == true then
            wait(0.1)
            print("Combat Enabled!")

        else
            print("Combat Disabled")
            -- break
        end
    end
end)()

Please accept and upvote this answer if it helps!

Ad

Answer this question