I have a script attached to a terrain that procedurally generates a forest that runs exponentially slowly as the area generated gets larger, from a reasonable 10 seconds total for 300 objects to an outlandish 10 minutes for 1700 objects. Putting the Instantiate call behind a simple stopwatch-print statement shows that it starts out at ~1ms for the first object and then climbs fairly consistently to 300ms. Probably irrelevant context: all of these objects use the same prefab (a 1500-vertex mesh) and they all need to have the same parent.
Why does Instantiate seem to run in On^3 or worse compared to the number of objects already instantiated? Is this an internal memory/gc issue? Is there a way to get Unity to manually flush the sort of object registry that could be causing this? Finally, is there a way to get the inbuilt profiler to work in edit mode?
Things I’ve tried: switching to new GameObject(), which seemed to have the exact same issue.
Edit: After more prying it is clear that the cause is the specific set of positions I’m giving the Instantiate call.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GameObject hex = Instantiate(hexPrefab, hexContainer);
stopwatch.Stop();
print("Instantiate took " + stopwatch.Elapsed);
stopwatch.Reset();
stopwatch.Start();
hex.transform.position = location;
stopwatch.Stop();
print("Moving and rotating took " + stopwatch.Elapsed);
In this code the Instantiate call itself continues getting slower after every call. Bizarrely, if the position change after the Instantiate call is commented out, then the Instantiate call continues at constant speed. I haven’t been able to reproduce this outside my own script yet. I will pry more in the next few days, but my only thoughts are that this could be caused by some sort of collision check or very consistent multithreading operation behind the scenes.