void UseDestroyForMonoBehaviours() { // cube primitive is created. GameObject gameCube = GameObject.CreatePrimitive(PrimitiveType.Cube); // the MonoBehaviour that scales the cube when the event is called // then destroys itself once countdown is less than 0 UsesOnDestroy monoDestroyer = gameCube.AddComponent <UsesOnDestroy>(); // dispatcher will call the event that the self destroying MonoBehaviour // is listening to. DestroyEventDispatcher destroyDispatcher = new DestroyEventDispatcher(); // the event dispatcher is assigned to the MonoBehaviour monoDestroyer.AssignListenerUpdater(destroyDispatcher); // there will be a cube for a moment after start // but it's destroyed almost right away. destroyDispatcher.CallUpdateListenerEvent(); }
/* * * * * * * * * * * * * * * * * * Section 7.17.3 The Ugly Truth * * * * * * * * * * * * * * * * * */ void UseDestroyTooMuch() { GameObject gameCube = GameObject.CreatePrimitive(PrimitiveType.Cube); UsesOnDestroy monoDestroyer = gameCube.AddComponent <UsesOnDestroy>(); DestroyEventDispatcher destroyDispatcher = new DestroyEventDispatcher(); monoDestroyer.AssignListenerUpdater(destroyDispatcher); // Calling the event 100 times. destroyDispatcher.CallUpdateListenerEventTooManyTimes(); // it should be gone, but it's still listening? destroyDispatcher.UpdateListenerEvent -= monoDestroyer.OnUpdateListener; // lets disconnect the event listener. Debug.Log("Calling event again"); // Calling the event 100 times. destroyDispatcher.CallUpdateListenerEventTooManyTimes(); Debug.Log("When will the UseOnDestroy script actually destroy itself?"); }