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

Question other.GetComponent<>().DoSomething() vs. local DoSomething()

Discussion in 'Physics' started by SeriouslyNot, Jun 28, 2020.

  1. SeriouslyNot

    SeriouslyNot

    Joined:
    Nov 24, 2017
    Posts:
    121
    I've been wondering a lot about this lately, i have a 2D game (Bricks game) where you shoot Bullets to hit Cubes, sometimes you have 200 bullets and 50 cubes, so i have ApplyDamage() method inside CubeController script and i want to call it whenever Cube gets hit by Bullet.

    But keep in mind that there are other types (not only Cubes), there are Coins and other stuff too.

    I'm doing this entirely inside the BulletController so i have only ONE OnCollisionEnter2D (i think this is cheaper than having multiple OnCollisionEnter2Ds?), i'm checking for a other.compareTag("Cube"), and i'm calling:
    other.gameObject.getComponent<CubeController>().ApplyDamage();

    Is it cheaper to have a standalone (EXTRA) OnCollisionEnter2D() inside CubeController and just call ApplyDamage() locally? I also need to do stuff on BulletController script as well so there will be two OnCollisionEnter2Ds, but there would be no GetComponent<>() calls.

    Is having an EXTRA OnCollisionEnter2D() expensive? because i guess it sends Physics information to the CPU.

    So to sum up:

    One OnCollisionEnter2D() with GetComponent<>() calls (with its local calculations as well)

    OR

    Multiple OnCollisionEnter2Ds with no GetComponent<>() calls?
    (each one will do its own local calculations)

    Which one is cheaper?