Delegates & Events registration & deregistration - Doubt
Hello,
Two Classes
ObjAEventHead.cs
ObjBEventListener.cs
SCENARIO :
Awake() & OnEnable() on ObjAEventHead.cs is called before Awake() & OnEnable() on ObjBEventListener.cs It is a wierd way Unity calls these methods. When I use Delegates, Events or Actions, my habit is to register a listener in OnEnable & DeRegister in OnDisable like in the below scripts.
ObjAEventHead.cs
using System.Collections;
using UnityEngine;
public class ObjAEventHead : MonoBehaviour
{
internal delegate bool? KeyPressHandlerWithReturnValue();
internal event KeyPressHandlerWithReturnValue OnKeyPress;
internal static event KeyPressHandlerWithReturnValue OnKeyPressStatic;
internal System.Action<bool> OnTestingAction;
float time = 0f;
private void Awake()
{
Debug.Log ("Obj A Awake");
}
private void OnEnable()
{
Debug.Log ("Obj A OnEnable");
}
private void OnLevelWasLoaded(int _index)
{
Debug.Log ("Obj A Level was loaded");
}
private IEnumerator Start()
{
while (true)
{
if (Input.GetKeyUp (KeyCode.A))
{
if (OnKeyPress != null)
{
var goat = OnKeyPress ();
// Only the last trigger module's return value is printed
Debug.Log (goat);
}
}
if (Input.GetKeyUp (KeyCode.S))
{
if (OnKeyPressStatic != null)
{ OnKeyPressStatic ();}
}
if (Input.GetKeyUp (KeyCode.B))
{
if(OnTestingAction != null)
{
OnTestingAction (true);
}
}
yield return null;
}
yield return null;
}
private void Listener()
{
}
private void OnDisable()
{
Debug.Log ("Obj A OnDisable");
}
private void OnDestroy()
{
Debug.Log ("Obj A OnDestroy");
}
}
ObjBEventListener.cs
using System.Collections;
using UnityEngine;
public class ObjBEventListener : MonoBehaviour
{
public ObjAEventHead ObjA;
private void Awake()
{
Debug.Log ("Obj B Awake");
}
private void OnEnable()
{
Debug.Log ("Obj B OnEnable");
ObjA.OnKeyPress += keyPressListenerFromObjA;
ObjA.OnTestingAction += onTestingAction;
}
private void onTestingAction (bool obj)
{
Debug.Log ("Action Received - " + obj);
}
private bool? keyPressListenerFromObjA ()
{
Debug.Log ("Obj B Listener");
return true;
}
private void Start()
{
}
private void OnDisable()
{
ObjA.OnKeyPress -= keyPressListenerFromObjA;
ObjA.OnTestingAction -= onTestingAction;
Debug.Log ("Obj B OnDisable");
}
private void Listener()
{
}
private void OnDestroy()
{
Debug.Log ("Obj B OnDestroy");
}
}
Question :
When OnDisable in ObjBEventListener.cs gets called OnDestroy in ObjAEventHead.cs has already run it's course. So would there be any problem if I try to deregister in OnDisable, like I have done below. NOTE - It doesnot throw null reference exception.
For building large projects, what is the best practice?
Thank you, Karsen
Your answer
Follow this Question
Related Questions
UnityAction Vs UnityEvent 1 Answer
How i make my player object passes through walls? 2 Answers
Read and Write Textfile on mobile (C# Unity ) 0 Answers