I have multiple events in my scripts that kinda ‘stack’, meaning if I loop it and then play the event, multiple results appear. How can I ‘reset’ the event everytime so it only sends one result?
local function ChooseTarget() -- This function will be called multiple times.
MaxActivationDistance(100) -- Ignore this. Nothing important.
for i,v in pairs (Enemies) do
v.Model.BattleInfo.Click.ClickDetector.MouseClick:Connect(function() -- This mouse event will stack, because of calling the function multiple times.
print(1)
WhichAttack.Attacker = Player.Character
WhichAttack.Target = v
game.ReplicatedStorage.BattleModules.BattleSystem.PlayerSendAttack:FireServer(WhichAttack) -- Eventually it will send multiple results than needed.
MaxActivationDistance(0)
end)
end
end
No because the event is still called. My solution here would be creating a global table (outside of the loop’s scope) and then inserting each connection into that array. From there, just make sure to disconnect each array value before making a new connection.
local globalVariable = {}; -- Variable outside the function's scope
local function ChooseTarget() -- This function will be called multiple times.
MaxActivationDistance(100) -- Ignore this. Nothing important.
for i,v in pairs (Enemies) do
v.Model.BattleInfo.Click.ClickDetector.MouseClick:Connect(function() -- This mouse event will stack, because of calling the function multiple times.
print(1)
WhichAttack.Attacker = Player.Character
WhichAttack.Target = v
game.ReplicatedStorage.BattleModules.BattleSystem.PlayerSendAttack:FireServer(WhichAttack) -- Eventually it will send multiple results than needed.
MaxActivationDistance(0)
end)
end
end