Search Unity

How to Activate/Deactivate many GameObjects

Discussion in 'Editor & General Support' started by MateoPeri, Aug 15, 2019.

  1. MateoPeri


    Oct 19, 2017

    I have a lot of GameObjects in my scene (more than 50k). At some point in the game, I need to activate or deactivate a lot of them.
    My goal is to achieve this smoothly and avoid lag spikes as much as possible.
    Doing this in one frame causes lag. Making them childs of an empty object and then deactivating that object leads to the same result.

    I thought about using multi-threading, but then I read that the Unity API is not thread-safe, so I wouldn't be able to modify the GameObjects' state in another thread.
    I also tried coroutines, but there was still noticeable lag.

    Is there a way to achieve this without lag, or is it plain impossible?

    Thanks in advance.
  2. Gambit-MSplitz


    May 16, 2015
    50K is a lot of objects! Are you sure you need that many?

    If they only need to appear hidden and don't need to be fully deactivated, you could either share a material across all of them with a property that disables rendering, or you could set a shader uniform that disables rendering in the shaders used by the 50k objects. That way, the CPU/GPU only needs to set a single value instead of setting a value per-object. I do not recommend using transparency because there is automatic z-sorting on transparent objects, and that will be very expensive for 50k objects. Instead, use the material property or shader uniform to determine if you should clip or discard your pixels in the shader.

    Good luck!
    breban1 likes this.
  3. AllanSmithZ3


    May 21, 2019
    You could also just move them out of the camera frustrum to get cheaply occluded, maybe use Job System which is multithreaded (dont remember now but pretty sure you could do this using jobs?)... I personally been moving stuff away to get the same effect because enabling/disabling game objects causes unity to update a lot of stuff under the hood, but, if you do use unity methods like Update you might not have this option, as those will keep running while the object is active, even if its occluded...

    You probably need to do this over a few frames as well, to reduce/control the spike, if at all possible... if completely unavoidable you might want to have some form of transitioning in your game... like elevator scenes to unload part of the game and load the next lol, this kind of cheap trick a lot of games use to hide the loading without loading bars.