I’m working on a project in which I have, as a requirement, 20K gameobjects instantiated that are always moving. Each gameobject has a script attached in which I can change its color, size, etc. Obviously, I get a poor performance. I’ve read that with Graphics.DrawMeshInstancedIndirect I can get a performance boost, but it only instantiate a mesh, not a prefab. Is there any other alternative so I can get a performance boost?
The code I’m using right now to instantiate is the following one:
public GameObject gameObjectPrefab;
public int numberOfInstances;
private void Start()
for (int i = 0; i < numberOfInstances; i++)
Vector3 randomPosition = new Vector3(Random.Range(-5000, 5000), Random.Range(-5000, 5000), Random.Range(-5000, 5000));
Instantiate(gameObjectPrefab, randomPosition , Quaternion.identity, transform);
I attach one screenshot taken from the profiler
I know you disagreed with @logicandchaos but if you are just changing color, position, and size you should be able to do this from a manager script without the need for a script on each object… in fact I’m having trouble thinking of much functionality that requires you to have a script on each game object, usually its done for convenience / organizational sake. But if you want 20k objects I really recommend trying to come up with a solution that only uses one script instance. AT THE VERY LEAST if your scripts have update functions (which I see that they do), call them from a manager script instead of having unity call them for you. This can result in a pretty significant performance boost by itself. Taking this a step further, this seems like the kind of thing that Unity’s DOTS system is perfect for. There is a bit of a learning curve, but it can really have incredible results, even with several hundred thousand entities.
If you post a screenshot of the script breakdown in the profiler (we can only see the top bit of it in the screenshot you posted) as well as the code in your update functions we could probably help you identify issues there as well.
If you create one script that manages all the objects it will be more efficient than each object having a script on it, especially if the script has an update on it.
@ratchetunity I have struggled with this problem in the past. What I do was to save the prefabs in “Inactive” so when i instantiate them Unity does it really fast. When all prefab are ready I make them “Active” and that’s all. Hope it helps.