Preserving C# event delegates on code change in Unity3D

While tooling around with Unity, C#’s event delegates have quickly become a standard part of my utility belt. They’re a great way to separate concerns and drive events in a typesafe way (as opposed to Unity’s built-in GameObject#SendMessage, which uses string method names), but I quickly noticed something frustrating: when I would make a code change while in play mode, all of my registered events would be lost, and I would have to stop and start the game to bring them back. It might seem minor, but I’m all about removing inconveniences during the development process, so after trying a few different things without success, I put the question out on Twitter. Big thanks to @catlikecoding for a quick answer: add your event handlers to the delegate in OnEnable instead of OnStart or OnAwake.

One thing to be aware of is that OnEnable can be called numerous times during the lifecycle of your game: when you start, when your code changes, and significantly, if you disable and re-enable a component. This last one can be the source of subtle bugs where your event handler will be called multiple times per event, so you should be careful to tear down events in OnDisable as well. Here’s some example code: