Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is the simplest way to have a script remove its self after an "onTouch" function?

Im creating a script to be removed after an onTouch function and Im not sure the right way to have it removed after its done. Can any one help me understand how the script needs to know that it was touched by a humanoid and it should remove its self?

local p = script.Parent


function onTouch(part)
    local HumanoidIsFound = part.Parent:FindFirstChild("Humanoid")
    local PlayerIsFound = game.Players:GetPlayerFromCharacter(part.Parent)
    if HumanoidIsFound and PlayerIsFound then
		wait(.5)
		PlayerIsFound.PlayerGui.ScreenGuitycoon.TextButton.Visible = true
		wait(1)
		PlayerIsFound.PlayerGui.ScreenGuispawn.TextButton.Visible = false
    end
end

p.Touched:connect(onTouch)

3 answers

✓ Accepted answer

The simplest way is not to remove it but to disable it script.Disabled=true think about it.

Simplicity is not equal to Efficiency.

The simplest, and probably most efficient way to make an event not activate more than once would be to use the disconnect method.

To do this you need to make a connection( i.e. connection statement ) and tie it to a variable. Then, you can use the disconnect method after the definition of your function.

local connection --Define it before, so it doesn't return 'nil' inside itself.

connection = p.Touched:connect(function(part)
	local plr = game.Players:GetPlayerFromCharacter(part.Parent)
	if plr then
		wait(.5)
		PlayerIsFound.PlayerGui.ScreenGuitycoon.TextButton.Visible = true
		wait(1)
		PlayerIsFound.PlayerGui.ScreenGuispawn.TextButton.Visible = false
		connection:disconnect() --disconnect the connection
	end
end)

2 comments

0

this is giving me the error that hit is unknown globally

0

It shouldn't be doing that. I don't even use 'hit' in my script.

The easiest way to get rid of something is to just use the Destroy method.

Like so:

game.Workspace.Part:Destroy()

Modified script:

local p = script.Parent


function onTouch(part)
    local HumanoidIsFound = part.Parent:FindFirstChild("Humanoid")
    local PlayerIsFound = game.Players:GetPlayerFromCharacter(part.Parent)
    if HumanoidIsFound and PlayerIsFound then
        wait(.5)
        PlayerIsFound.PlayerGui.ScreenGuitycoon.TextButton.Visible = true
        wait(1)
        PlayerIsFound.PlayerGui.ScreenGuispawn.TextButton.Visible = false
	script:Destroy--Added this
    end
end

p.Touched:connect(onTouch)

There other ways to remove stuff but this is the most straight-forward way.

This discussion is preserved as it was. New answers, comments, and votes are closed.