Search Unity

+100 Object, OnCollision performance optimization

Discussion in 'Scripting' started by Greetz443, Sep 17, 2020.

  1. Greetz443

    Greetz443

    Joined:
    Dec 20, 2019
    Posts:
    18
    Hi,

    i have a bigger scene with over 100 objects. When they collide they react and change color.

    Now what is better in terms of performance:

    1) The player gets an oncollision and gets the material component and changes it to the material at collision.

    2.)All objects get a script with oncollision and on contact they change their material (advantage: the renderer and the material is stored as public variable). Do the many oncollisions have a disadvantage and you have to load all public variables first, or is this just a cheap referencing?

    Most objects would be used during the game.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    The collision performance of 100 objects should not be a problem. Did you notice any problems?
    If not, just implement it in a way you prefer architecturally / for maintenance reasons. Who is doing the "color changing" logically? Are the objects changing their own color, ie to a predefined color saved in their script, or is it a property of the player to change the color of everything he touches (for example to red)? Decide who handles the color change based on that information. You want objects to contain the code they are actually responsible for.

    Also, what's "expensive" about collisions, is the collision checking itself. And Unity already optimized that for you. In both of your suggestions Unity needs to check for collisions, and on collision in both of your suggestions one OnCollision method is executed. So the performance should be absolutely identical anyways.

    Do not worry about performance unless you notice an actual problem. You most likely just spend time optimizing something that may never have become a problem in the first place, thus effectively wasting your time.
     
    Greetz443 likes this.