Search Unity

custom Event invocation leaves me puzzled

Discussion in 'Scripting' started by modellking, Sep 26, 2019.

  1. modellking

    modellking

    Joined:
    Apr 13, 2017
    Posts:
    3
    I'm utterly puzzled as to why this does only print "Am I stupid" and not "Listener"
    I hope this is minimal working example. No Errors or Exceptions. (on Unity 2019.1.2f1)

    Code (CSharp):
    1. public class TransformEvent : UnityEvent<Transform> {}
    2. public class ElementAdding : MonoBehaviour
    3. {
    4.     public TransformEvent OnAdd => new TransformEvent();
    5.     private void Start()
    6.     {
    7.         OnAdd.AddListener(_=>Debug.Log("Listener"));
    8.         OnAdd.Invoke(transform);
    9.         Debug.Log("Am I stupid?");
    10. }}
    Attaching a handler from another class and invoking from a button event yields the same result, so i do suspect, that it is not imporant to have a cycle between the addListener and the Invoke call.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    I'm unfamiliar with what the => in a class level declaration does... but it compiles and fails in the way you indicate.

    However if I change it to a simple class-level new assignment, it works as expected, as I would expect.

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEngine.Events;
    3.  
    4. public class TransformEvent : UnityEvent<Transform> {}
    5. public class ElementAdding : MonoBehaviour
    6. {
    7.     public TransformEvent OnAdd = new TransformEvent();
    8.     private void Start()
    9.     {
    10.         OnAdd.AddListener(_=>Debug.Log("Listener"));
    11.         OnAdd.Invoke(transform);
    12.         Debug.Log("Am I stupid?");
    13.     }
    14. }
    Screen Shot 2019-09-26 at 3.20.49 PM.png
     
    modellking likes this.
  3. modellking

    modellking

    Joined:
    Apr 13, 2017
    Posts:
    3
    You caught a typo i didn't realize was there... I am stupid apparently
    => on a field defines the following lambdy style expression as a getter, so each and every call to the OnAdd Field just gave me a new instance of the TransformEvent

    Thank you very much i spent hours hunting this
     
    Kurt-Dekker likes this.