Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I make it so that when a part is touched a GUI appears?

Asked by 1 year ago

I have tried multiple times to make it so that when a part is touched a GUI appears, waits 5 seconds, and then disappears and you can’t do it again. Could someone help me with this?

1 answer

Log in to vote
1
Answered by 1 year ago
Edited 1 year ago

Create a script inside the part and set the RunContext to the client, so it runs the code on the client side. Or you can use a local script and parent it to StarterGui; up to you.

Use a Touched event to detect when another part has touched the part. This event will return the part that came into contact.

Use a conditional statement to check if the part is a descendant of a Model; then check if the Model has a player object by using the Players:GetPlayerFromCharacter() method.

Obtain the GUI you wish to make visible from the player's PlayerGui; to make the GUI disappear after a certain amount of time, use a debounce in conjunction with a wait. You can also use delay (which I prefer), which will schedule a function to be called within the given time; when the function gets called, set the debounce back to false, allowing the code to run again.

local LocalPlayer = game.Players.LocalPlayer
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")

local Part = script.Parent

local Touched = false

Part.Touched:Connect(function(hit)

    local Model = hit:FindFirstAncestorOfClass("Model")
    if Model then

        local PlayerHit = game.Players:GetPlayerFromCharacter(Model)
        if PlayerHit == LocalPlayer then
            if Touched then return end

            Touched = true

            local GUI = PlayerGui.ScreenGui.Frame
            GUI.Visible = true

            task.delay(5, function()
                GUI.Visible = false
                Touched = false             
            end)
        end
    end
end)
1
I recommend using task.delay instead. It's slightly faster. T3_MasterGamer 2189 — 1y
0
Yeah, it is. Still getting in the habit of using the task library lol xInfinityBear 1777 — 1y
Ad

Answer this question