Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.