UI appear when part is touched, disappear when stepping off part

I have a script which is inside of a part, when the part is stepped on I want a UI to appear and I only want it to disappear when the player steps off the part.

I was struggling to find a way to detect when the player steps off a part as I was met by many mistakes and errors so I sticked to detecting when they are a certain amount of studs away, the UI goes invisible.

The script I’m currently using makes the UI appear shortly after stepping on it instead of checking the studs and only going invisible when its a certain amount of studs away. Any help on this would be appreciated or assistance on how to adjust the script so it detects when the player steps off the part then the UI goes invisible instead of using studs?

local part = script.Parent

part.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild('Humanoid') then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		local effectsFrame = player.PlayerGui.Frames.EffectsFrame
		local debounce = false -- Initialize debounce
		local distanceCheckInterval = 0.5
		local debounceDuration = 1 

		local function toggleVisibility(visibility)
			if debounce or effectsFrame.Visible == visibility then
				return
			end
			effectsFrame.Visible = visibility
			debounce = true
			wait(debounceDuration)
			debounce = false
		end

		toggleVisibility(true)

		while true do
			wait(distanceCheckInterval)
			if not part:IsDescendantOf(player.Character) or player:DistanceFromCharacter(part.Position) > 20 then
				toggleVisibility(false)
				break
			end
		end
	end
end)

Hi!

Have you tried the .TouchEnded() event?

I have, I found it very unreliable and found that the UI kept flickering whilst the user was on the part.

Just did a quick devforum search and found this post which found a solution to the exact same goal which you are trying to achieve.

local part = game.Workspace.Part
part.Touched:Connect(function(Hit)
	if Hit.Parent:FindFirstChild("Humanoid") then --// checks if its a player
		script.Parent.ScreenGui.MyGUI.Visible = true
		
		repeat task.wait() until (part.Position - Hit.Parent.HumanoidRootPart.Position).magnitude >= 6
		
		script.Parent.ScreenGui.MyGUI.Visible = false
	end
end)

Please let me know if this worked!

1 Like

That’s actually the post I based this script on :sweat_smile:, I tried this earlier didn’t seem to work either.

Did it return any errors or have any malfunctions that I should know of?

Oh wow, nevermind.

I adjusted the script so it got the UI from the player’s PlayerGui instead of directly from StarterGui and that seemed to work. Thanks alot!

No problem! Glad I could help.

1 Like

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