Currently, my game will spawn in a few enemies into the scene when a “wave” starts. This does not cause any lag, however, on each of the enemy, I have a script that tracks every single structures that belongs to the player (These structures are stored in an empty object so I used a foreach loop to get each structure’s position). After getting each of the position, the enemy will find the nearest structure to go to.
This itself is obvious that it will cause some lag, so I added a small timer to control the interval between finding a new nearest target (1 - 2 seconds). This helps with the frame drop issue as it is not tracking on every single frame.
However, taking a look at my profiler, at each tracking moments, it has a huge lag spike. When playing the game, you can feel that the enemies are all trying to track and find the nearest object to go to (As the game stops for a brief moment, normally around 0.1 seconds).
Is there a way I can optimize this? I have some solution in mind though, as I am using a for loop to instantiate all of the enemies in the scene at once, I’m pretty sure this will cause that future tracking “moments” will happen for all of the enemies since they are spawned in at the same time. So would spawning them in at different times help.
Are there any other better way to improve the code?
private void track_items()
{
small_timer -= Time.deltaTime;
if (small_timer <= 0)
{
foreach (Transform structure in mc_structures.transform)
{
tracked_items.Add(structure);
}
foreach (Transform o in tracked_items)
{
float dist = Vector2.Distance(o.position, transform.position);
if (o.name.Equals("main_character"))
{
dist /= 2;
}
if (dist < distance)
{
distance = dist;
target = o.gameObject;
}
}
small_timer = small_time;
}
}
small_time is set to 2 seconds.
Also, I added a if statement to make the enemies more “interested” in the player.
mc_structure is the empty game objects that all of the structures will be stored in.
Thanks for the help.