0

I have a CSV with the following columns: time, carId, x, y. I am writing a script which will read the CSV and spawn car objects and simply update their positions over time based on the data.

Over the span of about 20 minutes, around 3500 car objects will have to have been instantiated. While they won't all be in the simulation at one point in time (once a car gets to certain points in my road network, it will disappear), but I want to be prepared for a situation where hundreds of car objects move through the network at once.

I'm still new to Unity and its rendering pipeline when it comes to optimizing for this big of a project. I know in some cases it's better to setActive(false) on GameObjects as opposed to destroy() and maybe this is one of them. What else should I consider when handling this many gameobjects in Unity?

rafvasq
  • 1,512
  • 3
  • 18
  • 48
  • 1
    Why not just spawn them as needed? Throw the data into an array, use it when it's needed. Destroy un-needed objects... – Trey May 31 '18 at 20:45
  • @Trey thanks for the comment. That's exactly how I plan to do it. I just assumed that it wouldn't run as smoothly as it sounds with that many objects in consideration – rafvasq May 31 '18 at 20:47
  • 1
    If you are looking at spawning that many objects, you may want to look into [object pooling](https://www.raywenderlich.com/136091/object-pooling-unity). – Lews Therin May 31 '18 at 20:48

2 Answers2

2

This sounds like a great opportunity to use Object Pooling. You are on the right track with using setActive.

Follow this short tutorial : https://unity3d.com/learn/tutorials/topics/scripting/object-pooling

It should reduce a lot of the lag you would get by instantiating/ destroying a lot of objects.

Immorality
  • 2,164
  • 2
  • 12
  • 24
  • 1
    I upvoted, but answers shouldn't be link-only (in case the link goes down in the future). I'd recommend at least adding a very simple example of object pooling (which is why I only added a comment and not an answer :)) – Lews Therin May 31 '18 at 20:51
2

What else should I consider when handling this many gameobjects in Unity?

For the most part, this really depends on the amount of Objects or cars that will be displayed at the same time on the screen.

If it's just few cars then use Object Pooling to recycle the Objects.

You should also use LOD to optimize and reduce the number of triangles rendered for an object.


If it's a traffic simulation with hundreds of cars moving at the same time then you should use GPU Instancing which is now built into Unity. To enable GPU, use a Standard Shader and check the "Enable GPU Instancing" box.

enter image description here

After enabling it on the material, you can use Graphics.DrawMeshInstanced to instantiate the Objects and MaterialPropertyBlock to change how they look.

rafvasq
  • 1,512
  • 3
  • 18
  • 48
Programmer
  • 121,791
  • 22
  • 236
  • 328