I am currently working on a little RTS game project, and I have finished most of the basic unit movement, interactions etc. framework, and I am now moving onto optimization and visuals. The game is Filtering Enabled, and all movement and interaction calculations are done by individual clients. I am currently finding the most CPU usage coming from my method of finding objects in proximity to the individual units. I currently have it where all the units and their basic values such as ID, owner, current waypoint etc, are all stored within a table within each client. However, I am currently using FindPartsInRegion3witIgnoreList and the good old fashion .magnitude to find the distance between the units. Currently, I have it where every 1 second it updates all the units and their interactions, but the tables containing nearby and the nearest enemy/ally is updated every 2 seconds, and I am using (tick() - lastupdate) to achieve the multiple timings within one loop. Whenever I deactivate the finding of nearby and nearest units the script runs very well with minimal CPU usage, however when this function is in use at this interval, it can get up to 6% CPU usage when two players have 50 units, and they are all in very close proximity. So finally to my question, is there any other ways to optimize this system? I was wondering if there are any other methods to find the nearest objects or iterate through a table of existent objects. Any advice would be great. Below is my current code:
local function findNearestID(unit,point,range)
local closestally = nil
local closestenemy = nil
local closestenemydist
local closestallydist
local ally,enemy = {},{}
local unitpos
local objs = Objects:GetChildren()--AllUnits
if unit == nil then
unitpos = point
else
unitpos = unit.Position
objs = ObjsRegion3PS(unitpos,unit.Range.Value*Vector3.new(1,1,1))
--ObjsRegion3PS finds all parts in Region3 centered at point and range
range = unit.Range.Value
end
for i =1, (#objs) do
if objs[i] ~= 0 then
local obj = objs[i]--[1]
if obj ~= unit and obj:FindFirstChild("ID") then
local mag = (obj.Position - unitpos).magnitude
local comparison = (closestallydist or 1000)
local comparison2 = (closestenemydist or 1000)
local ID = obj.ID.Value
local splr = obj.Owner.Value
if splr ~= plr and range > mag then
table.insert(enemy,{obj,ID,splr})--objs[i])
if mag <= comparison2 then
closestenemy = ID
closestenemydist = mag;
end
elseif range > mag then
table.insert(ally,{obj,ID,splr})--objs[i])
if mag <= comparison then
closestally = ID
closestallydist = mag;
end
end
end
end
end
return ally,enemy,closestally,closestenemy
end

1 comment
I just realized I was changing values in the interactions function which was really CPU intensive, this is actually pretty efficient already.