:IsKeyDown() not being detected as false

This is all in a localscript within a tool. I want the localscript to run a number that goes up from 0 to 100 as the player holds down the letter E. If the player lets go in between, the number stops where it’s at. Simple power level system. Everything works perfectly EXCEPT for the part where the number ends when the player lets go of the key. This is due to the script never detecting when :IsKeyDown() is no longer true. How many I fix this? Script provided below.

local function onPowerScroll(button, track, event) -- event is the main RemoteEvent
	local PwrChangeRE = event.PowerChangeRE
	local PwrHeldRE = event.PowerHeldRE
	local PwrReleaseRE = event.PowerReleaseRE
	
	local powerDone = false
	
	PwrHeldRE:FireServer()
	
	
	for power = 0, 100, 1 do
		if power < 100 then
			if button then -- button being UserInputService:IsKeyDown(Enum.Keycode.E)
				print("it aint over bro")
			elseif not button then
				print("its over! send to server!")
				PwrReleaseRE:FireServer()
				onAction(track, event) -- no need for the context to this function
				break
			end
		elseif power == 100 then
			print("power is 100! tell the server!")
			PwrReleaseRE:FireServer()
			onAction(track, event) -- no need for the context to this function
			break
		end
		task.wait(0.00001)
	end
end
1 Like

The loop will be referring to the value that button was when the function first started running. If you need it to reflect the real-time value that would be returned from the :IsKeyDown() call, the variable would need to be updated.


In this case, you could re-assign UserInputService:IsKeyDown(Enum.KeyCode.E) to the button variable at the very beginning of the loop so it re-checks it each time. Alternatively, you could have an InputEnded event connected to a completely separate function that would update a variable at the top of the script to indicate whether or not the player is holding down a particular key, and then have the loop refer to that variable since it would be being updated by the other function.

The specific implementation of this will vary slightly depending on if the button being pressed down that the function needs to check for will always be Enum.KeyCode.E or if it could vary. If it could vary, you could have the server script send through the KeyCode in place of button so that the loop can check what the value of UserInputService:IsKeyDown(button) is during each iteration of the loop.

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