Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question How to listen for Events without using OnEnable() function??

Discussion in 'Scripting' started by SajorDev, May 16, 2024.

  1. SajorDev

    SajorDev

    Joined:
    Mar 13, 2023
    Posts:
    7
    I need to listen for an Event trigger but I can't use the OnEnable() function because I am using ML Agents and the OnEnable() function on the Agent parent class is protected where else can I place the Event receiver if I can't use OnEnable(), any suggestion would be welcome, thanks.
     
  2. mahdi_jeddi

    mahdi_jeddi

    Joined:
    Jul 18, 2016
    Posts:
    248
    Maybe make a second script that has the OnEnable, attached to the same object and calls the method you want from this main script. You could either pass a reference of the main script to this one or us UnityEvent field and set it up in the inspector.
     
  3. Sluggy

    Sluggy

    Joined:
    Nov 27, 2012
    Posts:
    1,017
    You can also just use the constructor. As long as you're not accessing any Unity API or assigning values that will be overwritten by the serialization system it'll work fine.
     
  4. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,189
    Uhm, because it IS protected you actually CAN override it. That's the point of it being protected. It if were decared private you could not override it. Well you could reimplement it but that would of course hide the original. That's why they declared most Unity callbace as virtual protected. Whenever you create a MonoBehaviour base class, this should be the default, otherwise a derived class can not implement those callbacks.

    Don't forget to call the base implementation, otherwise the class may not function as it should. This is actually mentioned in the comment at the OnEnabled method.

    Code (CSharp):
    1. public class YourAgent : Agent
    2. {
    3.     protected override void OnEnable()
    4.     {
    5.         base.OnEnable();
    6.         // additional OnEnable logic...
    7.     }
    8. }