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)
public class TransformEvent : UnityEvent<Transform> {}
public class ElementAdding : MonoBehaviour
{
public TransformEvent OnAdd => new TransformEvent();
private void Start()
{
OnAdd.AddListener(_=>Debug.Log("Listener"));
OnAdd.Invoke(transform);
Debug.Log("Am I stupid?");
}}
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.
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.
using UnityEngine;
using UnityEngine.Events;
public class TransformEvent : UnityEvent<Transform> {}
public class ElementAdding : MonoBehaviour
{
public TransformEvent OnAdd = new TransformEvent();
private void Start()
{
OnAdd.AddListener(_=>Debug.Log("Listener"));
OnAdd.Invoke(transform);
Debug.Log("Am I stupid?");
}
}
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