So i have a code below where it moves units to players mouse click position. But the more unit (can be up to 45 units) in the game the more lag it causes and its annoying and starting to get unplayable because the units sometimes just stops randomly and continue moving when theres too many units. So heres the code below:
Unit Move Code:
local playingAnim = false
game.ReplicatedStorage.Events.UnitControl.OnServerEvent:Connect(function(plr, mousepos, selected)
player = plr
if selected then
if debounce == false then
if selected:FindFirstChild("Moving") and selected:FindFirstChild("Humanoid") then
if selected:FindFirstChild("Moving") then
selected.Moving.Value = true
end
print("start move")
selected.Humanoid:MoveTo(mousepos)
selected.Humanoid.MoveToFinished:Wait()
print("finish move")
if selected:FindFirstChild("Moving") then
selected.Moving.Value = false
end
game.ReplicatedStorage.Events.UnitReaches:FireClient(plr)
end
end
end
end)
Mouse Click Code:
mouse.Button1Down:Connect(function()
wait(0.06)
if db == true then
return
end
if #selected > 0 and script.Parent.PlaceHolder.Value == false then
for i, part in ipairs(selected) do
if mouse.Target then
if not mouse.Target.Parent:FindFirstChild("Humanoid") then
game.ReplicatedStorage.Events.UnitControl:FireServer(mouse.Hit.p, part)
end
end
end
db = true
if not mouse.Target.Parent:FindFirstChild("Humanoid") then
posIndicator.BillboardGui.Enabled = true
posIndicator.Position = mouse.Hit.p
end
wait(cooldown)
db = false
elseif #selected <= 0 then
script.Parent.UnitIT.Visible = false
end
--and mouse.Target.Parent.team.Value == player.team.Value
if mouse.Target then
if mouse.Target.Parent:FindFirstChild("Humanoid") and not mouse.Target.Parent:FindFirstChild("Building") and not game.Players:FindFirstChild(mouse.Target.Name) and mouse.Target.Parent:FindFirstChild("Moving") and mouse.Target.Parent.team.Value == player.team.Value then
table.insert(selected, mouse.Target.Parent)
script.Parent.UnitIT.Visible = true
mouse.Target.Parent.UpperTorso.BillboardGui.Enabled = true
end
end
end)
And if you still not sure what im talking about, try yourself and play with a bot until you and the bot have many units