Search Unity

Question Hook into button clicks on Unity

Discussion in 'Scripting' started by unity2octro, Mar 22, 2023.

  1. unity2octro

    unity2octro

    Joined:
    Sep 12, 2022
    Posts:
    3
    Can I hook into all click events in Unity?

    We would want to remember the UI action trail, to send to Crashlytics in case of a crash. We can individually go into the button click events, 100s of buttons in various scenes, and write an function in there, like MyDebug.LogAction(), but I was wondering IF it is possible to centrally hook into all clicks.

    Sort of like how someone in C++ can hook into new operator (overload it), to e.g. do some debug time tracing of memory issues.
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,006
    Overloading an operator is not the same as hooking into a method call. When you overload an operator the compiler will actually use this operator instead of the default one. You can of course subclass your Buttons and replace all buttons to intercept all on click actions.

    Apart from that you can of course register a callback to all on click events of all buttons in the scene. However this is probably not what you want to do since if multiple callbacks are registered to an event, they are executed in order, one after the other. So if your crashlytics log comes after the callback that actually causes a crash, it would not be executed which kinda defeats the purpose you had in mind. So your best option is to use your own Button subclass. You can override the OnPointerClick method and OnSubmit method and insert your logging there.

    Of course you have to replace all your Buttons with your own subclass. You can actually inplace replace the classes by using the debug mode of the inspector. It allows you to replace the script in the script field which would essentially "convert" the component into the new type but keep serialized data.