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 1 year ago
Edited 1 year 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)

events.SampleEvent.OnClientEvent:Connect(function(sampleModel)
    game.Workspace.OnPlacementEvent.Value = true

    for _, unit in pairs(game.Workspace.MainZone:GetChildren()) do  
        unit.Main.SurfaceGui.TextButton.Visible = true

        unit.Main.SurfaceGui.TextButton.MouseEnter:Connect(function()

            sampleModel:PivotTo(CFrame.new(unit.Main.Position.X, unit.Main.Position.Y+1, unit.Main.Position.Z))

            for _, part in pairs(sampleModel:GetChildren()) do
                part.Transparency = 0.5             
            end
        end)    
    end
end)

1 answer

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

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

local connections = {}
events.SampleEvent.OnClientEvent:Connect(function(sampleModel)
    workspace:WaitForChild("OnPlacementEvent").Value = true

    for , unit in ipairs(workspace:WaitForChild("MainZone"):GetChildren()) do  
        unit.Main.SurfaceGui.TextButton.Visible = true

        local connection = connections[unit.Name]
        if connection ~= nil then -- if MouseEnter is still connected
            connection:Disconnect()
            connections[unit.Name] = nil -- removes connection from the dictionary
            connection = nil
        end

        -- creates a new connection/connects it again
        connection = unit.Main.SurfaceGui.TextButton.MouseEnter:Connect(function()
            sampleModel:PivotTo(CFrame.new(unit.Main.Position.X, unit.Main.Position.Y+1, unit.Main.Position.Z))

            for _, part in ipairs(sampleModel:GetChildren()) do
                if part:IsA("BasePart") then
                    part.Transparency = 0.5
                end
            end
        end)

        connections[unit.Name] = connection -- adds the connection to the dictionary

        unit.Destroying:Once(function() -- when unit is about to get destroyed
            local connection1 = connections[unit.Name]
            if connection1 ~= nil then
                connection1:Disconnect()
                connections[unit.Name] = nil
            end
        end)
    end
end)
Ad

Answer this question