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

Is there a way to check if a player is touching an object?

Asked by 10 years ago
gui = script.Parent.Text:Clone()
enabled = true

function onTouch(hit) 
    player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player ~= nil and enabled == true then
        enabled = false
        for k, v in pairs(player.PlayerGui:GetChildren()) do
            if v.Name == "Text" then
                v.Parent = nil
            end
            wait()
        end
        wait(0.5)
        gui.Parent = player.PlayerGui
        wait(3)
        enabled = true
    end
end 

script.Parent.Touched:connect(onTouch)

This script wipes out existing guis in the PlayerGui named "Text" and replaces it with another gui. However, complications arise when a player continues to touch the object. It will register the touch again, wiping out the existing gui and put it back, creating an unappealing "blinking" effect (gui being deleted and replaced over and over). To avoid this, I want the script to wipe out the guis in PlayerGui ONCE but keep the cloned gui in PlayerGui until the player is no longer touching the object. Is this possible? If so, how?

1 answer

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

Just add a check that makes sure the GUI is not already in existence before proceeding;

--Notice my use of WaitForChild. This makes sure that the PlayerGui is loaded before using it, helping to prevent errors.
if not player:WaitForChild("PlayerGui"):FindFirstChild(gui.Name) then
    --code
end

Also, since you cloned the gui once at the top of the script, there will only ever be a single clone created. The variable will never vary - it will always equal the same object. This will create an odd effect where only the player who touched the part last will be able to see the gui - it will jump from player to player each time a new person touches the part.

Just clone the gui inside the function.


A better way to destroy object is to use the Destroy() method. Objects with nil parents technically still exist and are taking up space, causing more lag.

0
Thanks! I just have one question, where in the script should I place the lines that check if the GUI is in existance? IcyArticunoX 355 — 10y
0
You could just add it into the if statement on line 06 with another and. Just make sure it comes after you check if the player exists. It can be in the same if statement, but don't plop it at the beginning. Perci1 4988 — 10y
Ad

Answer this question