Detect when player presses key while touching block

Hi, I’m trying to make it so when the player is touching a block and presses the space key the player’s health gets set to 0, only if they press space and touching it. However nothing seems to happen and there are no errors in the output, I’ve looked on the devforum and other places but I found nothing and I’m just stuck on what to do.

local block = script.Parent
local humanoid

local function onTouch(otherPart)
	local character = otherPart.Parent
	humanoid = character:FindFirstChildWhichIsA("Humanoid")
end

local function onInput(input)
	if input.KeyCode == Enum.KeyCode.Space and humanoid then
		humanoid.Health = 0
	end
end

block.Touched:Connect(onTouch)
game:GetService("UserInputService").InputBegan:Connect(onInput)

Any help would be grateful, thanks.

1 Like

first off,. UserInputService works only from local script.
I see what you were trying to do, you could make script that on TouchBegan makes StringValue Instance inside player’s character whith name touching or something, and on TouchEnded stops, then you can do that onInput in local script and check if player has that StringValue.

2 Likes

Okay, so I did stuff similar to what you said and got it working! Thanks

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