Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Managing update frequency of objects at runtime

Discussion in 'Scripting' started by nickyoso1, Dec 24, 2016.

  1. nickyoso1

    nickyoso1

    Joined:
    May 2, 2011
    Posts:
    85
    Hi guys, I have a situation for which I so far have not found a decent solution.

    My scene is divided into regions and each region has a list of the objects in that region that it manages. I want the update frequency of a regions objects to depend on the distance to the player, I want all objects to be updated but the objects far away aren't visible so they can be updated less frequent than the objects that are close to the player.

    There are several ideas that I have been playing around with.
    Option A:
    A region updates its objects every x ms, so for example:
    Region 1: updates every 5ms.
    Region 2: updates every 1000ms.
    Region 3: updates every frame.

    This one seems easy enough to implement, but because of how it is timed there are going to be moments where all regions are going to updates all their objects in the same frame. If you have thousands of objects this will have a big performance impact.
    So that's when I thought of the following option.

    Option B:
    A region updates x amount of objects every frame, so for example:
    Region 1: updates max 250 objects per frame.
    Region 2: updates max 50 objects per frame.
    Region 3: updates all objects per frame.

    This option distributed the load over multiple frames but implementation wise it is a bit more difficult than that.
    I could give the objects a variable TimeSinceLastUpdate, but I would have to update that every frame by adding Time.deltaTime and I don't know the performance impact of that on thousands of objects.
    The other way I could do it is by having a variable TimeOfLastUpdate in the objects, and also somewhere keeping track of the time in ms since the game started. That way whenever I update the objects I can supply them with the time since the game started in ms and they can simply subtract the values from each other to find out how much time has passed since the last update.

    I was hoping to get your thought on my ideas and maybe someone knows a better solution than what I have come up with so far.