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 Performance? OnBecameVisible() vs OnTriggerStay2D(Collider2D)

Discussion in 'Scripting' started by KarlKarl2000, Sep 12, 2020.

  1. KarlKarl2000

    KarlKarl2000

    Joined:
    Jan 25, 2016
    Posts:
    606
    Hi,

    I was thinking about this a bit today.

    I need my character to update a BOOL when a certain game object is nearby. Is it more performant to use OnBecameVisible() instead of OnTriggerStay\OnTriggerEnter?

    Thanks!:)
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    The two functions do very different things. OnTriggerEnter is triggered once when some object with a collider enters your trigger zone. Whether or not and when it triggers depends solely on the two collider shapes used. OnBecameVisible is a method called when an object enters the field of vision of any renderer. So which one to use depends on what you want to do, not their performance. You said you wanted to be notified when one object gets close to another. Use a trigger. OnBecameVisible has nothing to do with that.
    If this is about interaction (opening a door, picking up items, ..) use a raycast from the player instead.

    That said, do not worry about performance unless there is some actual performance problem you can profile. If we are really just talking about one object being informed about another object it does not matter the slightest. If we are talking about hundreds or thousands of objects, then sure, let's talk about performance.
     
  3. KarlKarl2000

    KarlKarl2000

    Joined:
    Jan 25, 2016
    Posts:
    606
    Ok good to know.
    Thanks for the clarification! :)