Search Unity

What goes under the hood of MonoBehavior.OnMouseOver?

Discussion in 'Scripting' started by hovgaardgames, Apr 30, 2021.

  1. hovgaardgames

    hovgaardgames

    Joined:
    Apr 30, 2019
    Posts:
    4
    Hi there,

    I'm curious to know what kind of optimizations goes into the OnMouseOver, OnMouseExit, etc. methods.

    When handling those events on multiple gameObjects, I've usually been doing a single Raycast on a parent object, for performance reasons.

    However, I recently noticed that the OnMouseOver event only allows a single object to be "hovered" at the same time, telling me it's not just a flat "1x raycast per object" implementation.

    So my question goes:
    Is the OnMouseX methods optimized to be used in multiple objects in a performant way, or is manual raycasting still preferred?

    Thanks!
     
  2. There isn't official details about this as far as I know, but the most probable educated guess is as follows:
    Unity probably gather all the MonoBehaviours, if finds any OnMouse*/OnPointer* methods, registers it on the engine side.
    Every frame the engine makes a raycast against the colliders belong to these objects, if finds any viable, calls the proper methods and saving the bookkeeping (if any enter or exit took place...).
    AFAIK it is nothing fancy, just an ordinary raycast per frame and selecting the closest viable one to the camera and calling exit/enter if needs any.

    You can run some tests yourself if you're concerned about it:
    - make a new project, add some numerous objects to it without any OnMouse* methods and measure the performance
    - add OnMouse methods to one object and measure again
    - add OnMouse methods to all of them and measure again

    In theory you shouldn't see any more performance penalty when you have one OnMouse method versus when you have numerous. At least not concerning amount of change.