Search Unity

  1. Click here to see what's on sale for the "Best of Super Sale" on the Asset Store
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Help Wanted Performance? OnBecameVisible() vs OnTriggerStay2D(Collider2D)

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

  1. AL_W

    AL_W

    Joined:
    Jan 25, 2016
    Posts:
    336
    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:
    1,734
    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. AL_W

    AL_W

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