Coroutine unable to fire when event invokes wrong instance after disabling Domain Reloading.

Hi,

I have a script that has a function that is called from an event, and within that function a coroutine is started. The first time loading playmode after making a script change and having the assemblies reloaded, the function works just fine, but when play mode is disabled and the re-enabled the function no long works. If I re-enable domain reloading, this issue doesn’t occur.

I tried marking the event registration with [InitializeOnEnterPlayMode] but it didn’t solve the issue. Any insight is greatly appreciated:

public class TestClass : MonoBehaviour
{
	public static TestClass instance;
	
	void Awake(){
		instance = this;
		Debug.Log(this); // works correctly 
	}
	
	void Start(){
		RegisterEvents();
	}
	
	void RegisterEvents(){
	   EventClass.testEvent += TestFunction;
	}
	
	TestFunction(){
		Debug.Log(this); // returns null on second playthrough
		StartCoroutine(TestCoroutine()); // errors here
}


public static class EventClass {
	public delegate void TestFunc();
	public static event TestFunc testEvent;
	
	public static void DoTestEvent(){
		testEvent?.Invoke();
	}

}

public class SomeOtherClass : MonoBehaviour
{
	void SomeOtherFunction(){
		   EventClass.DoTestEvent();
	}
}

The odd part is that I use this same functionality for other pieces but it works correctly, and I can’t tell where the issue might be originating. On the second playthrough this error gets thrown when the coroutine is called:

“MissingReferenceException: The object of type ‘TestClass’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.”

I’m certain I’m not destroying the class in script.

Unregistering the events in OnDisable() solved the issue.