I want to run a code if the player is touching a certain part but it just doesn’t work the way I want it to.
I do not want to run the code after the player touches it. I want to run it while the player is touching. That’s what I’m trying to achieve. My code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HatchEggEvent = ReplicatedStorage:WaitForChild("EggEvents").HatchEggEvent
local UIS = game:GetService("UserInputService")
local hatchKey = "E"
local player = game.Players.LocalPlayer
game.Workspace.HitBox.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
UIS.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode[hatchKey] then
HatchEggEvent:FireServer()
print("Fired!")
end
end)
end
end)
When I run through the part and come outside the part, and then click ‘e’ it prints “Fired!” I also know why this is happening but I do not know to solve this. Is there any way to check if the player is currently touching a part? Thanks.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HatchEggEvent = ReplicatedStorage:WaitForChild("EggEvents").HatchEggEvent
local UIS = game:GetService("UserInputService")
local hatchKey = "E"
local player = game.Players.LocalPlayer
game.Workspace.HitBox.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
UIS.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode[hatchKey] and (player.Character.HumanoidRootPart.Position - Hatcher.Position).magnitude < distance then
HatchEggEvent:FireServer()
print("Fired!")
end
end)
end
end)
I defined the variables you gave but nothing happens when I click ‘e’
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HatchEggEvent = ReplicatedStorage:WaitForChild("EggEvents").HatchEggEvent
local UIS = game:GetService("UserInputService")
local hatchKey = "E"
local player = game.Players.LocalPlayer
local Hatcher = game.Workspace.Egg
local Distance = 10
game.Workspace.HitBox.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
UIS.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode[hatchKey] and (player.Character.HumanoidRootPart.Position - Hatcher.Position).magnitude > Distance then
HatchEggEvent:FireServer()
print("Fired!")
end
end)
end
end)