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

How can I make a function work only once or just destroy itself?

Asked by 2 years ago
Edited 2 years ago

So I have this script that moves sample model, but the thing is whenever I create another sample model, the previous one is still attached to the function so it looks like previous model is same as new model (I hope you understand)

01events.SampleEvent.OnClientEvent:Connect(function(sampleModel)
02    game.Workspace.OnPlacementEvent.Value = true
03 
04    for _, unit in pairs(game.Workspace.MainZone:GetChildren()) do 
05        unit.Main.SurfaceGui.TextButton.Visible = true
06 
07        unit.Main.SurfaceGui.TextButton.MouseEnter:Connect(function()
08 
09            sampleModel:PivotTo(CFrame.new(unit.Main.Position.X, unit.Main.Position.Y+1, unit.Main.Position.Z))
10 
11            for _, part in pairs(sampleModel:GetChildren()) do
12                part.Transparency = 0.5            
13            end
14        end)   
15    end
16end)

1 answer

Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

You can use RBXScriptConnection:Disconnect() and connect it again.

01local connections = {}
02events.SampleEvent.OnClientEvent:Connect(function(sampleModel)
03    workspace:WaitForChild("OnPlacementEvent").Value = true
04 
05    for , unit in ipairs(workspace:WaitForChild("MainZone"):GetChildren()) do 
06        unit.Main.SurfaceGui.TextButton.Visible = true
07 
08        local connection = connections[unit.Name]
09        if connection ~= nil then -- if MouseEnter is still connected
10            connection:Disconnect()
11            connections[unit.Name] = nil -- removes connection from the dictionary
12            connection = nil
13        end
14 
15        -- creates a new connection/connects it again
View all 36 lines...
Ad

Answer this question