Trouble with delegates/ events in Unity

Viewed 1522

I've been having trouble with using delegates and events in Unity. I am familiar with subscribing and unsubscribing.

The problem i have is a stack overflow exception. However my Console outputs another message while not even in playmode. I am confident this log is tied to the stackoverflow exception, because it happened at the same time. What is also curious, is that the error just started happening, without me touching that part of the code for a while. I changed nothing in the subscribing of the event. Note that i had this exact same problem earlier in another project and ended up ditching event subscription.

Do note, i am not talking about the UnityEvent. I'm talking about the scripting delegate & event.

Here is a screenshot of the error i am getting while the game is not running.

Here is the definition of the delegate and event code:

public delegate void gameStart();
public event gameStart OnGameStart;

public delegate void gameEnd();
public event gameEnd OnGameEnd;

Here is a subscriber:

public override void OnInitialize()
{
    GameManager.Instance.OnGameEnd += StopSound;
    GameManager.Instance.OnGameStart += PlaySwipeClip;
}

public void PlaySound(AudioClip clip, bool doNotStopCurrent = false)
{
    if (doNotStopCurrent)
    {
        popupAudioSource.clip = clip;
        popupAudioSource.Play();
     //   AudioSource.PlayClipAtPoint(clip, Vector3.zero, 1f);
    }
    else
    {
        mainAudioSource.clip = clip;
        mainAudioSource.Play();
    }
}

public void PlaySwipeClip()
{
    mainAudioSource.clip = SwipeClip;
    mainAudioSource.Play();
}

I Only subscribe to the events once (I use the singleton pattern, OnInitialize() is called in Awake()). I am positive that the subscription does not happen twice.

I never unsubscribe to the events. Reason for this is that I use the same scene and "Manager" objects for the entire app's lifecycle. Is there something I am missing here? Should i unsubscribe in the OnDestroy?

Somehow i have a feeling that subscriptions are persistent between the lifecycles. The error goes away for a while when i rename the event variable.

Also I have tried setting all the events to null explicitly in the awake method, however this does not seem to resolve anything.

1 Answers

You have to unsubscribe otherwise you will leak memory. It is recommended to subscribe OnEnable() and unsubscribe OnDisable().

Related