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)
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)
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.