Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[SOLVED] How can I create my own Unity events such as Awake or OnEnable?

Discussion in 'Scripting' started by Deleted User, Mar 19, 2015.

  1. Deleted User

    Deleted User

    Guest

  2. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,738
    it is using SendMessage which is accomplishing this useing the Reflection feature of .net

    i really never used it, since i find the whole Delegates and events is just better, and if you look at the more modern parts of unity you will see that even unity tech is moveing towards using events, interfaces and delegates.
     
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Do you have official documentation that this is the case? I doubt it is because SendMessage does not target a specific MonoBehaviour. This would also seem to not jive with the fact that certain methods can be a coroutine and it would suggest that extensive use of Update would cause performance to be affected adversely.

    I had heard that the engine reflects against MonoBehaviour derivatives once in order to determine what class has what "events". The results are cached so the methods can be invoked directly.
     
    BenZed likes this.
  4. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,519
    Bunny83's description of how MonoBehaviour is implemented is the closest to official I've found.

    But why not use Unity's new Event System? It gives you much better signature validation. You're not vulnerable to typos in the method name string, and if your method expects an int and you pass it a string, the compiler will warn you.

    For example, take this:
    Code (csharp):
    1. public void LogMe(int x) {
    2.     Debug.Log("My int is: " + x);
    3. }
    4.  
    5. SendMessage("LogMeeee", "aString");
    You won't get any indication that the method name is wrong and the parameter type is wrong until runtime.

    Compare it to this:
    Code (csharp):
    1. public interface ILogMe : IEventSystemHandler {
    2.     void LogMe(int x);
    3. }
    4.  
    5. public class MyClass : MonoBehaviour, ILogMe {
    6.     public void LogMe(int x) {
    7.         Debug.Log("My int is: " + x);
    8.     }
    9. }
    10.  
    11. ExecuteEvents.Execute<ILogMe>(target, null, (x,y)=>x.LogMe(42));
    The compiler requires that everything is correct at compile time. As a bonus, it's faster than SendMessage.
     
    Deleted User and Schneider21 like this.