Diagnosing Keep-Alive events in Unity

Paul Marsh
2 min readApr 25, 2021
Just another bug hunt

One of the tricky bugs to diagnose is why an object is hanging around when you think it should have gone. Once reason for this is how .net maintains the life time of objects. .Net won’t automatically remove an object if something still has a reference to it. But when you have removed all the references and that object is still mysteriously still alive there is a common cause for this, dangling events.

Events

If the object, that is stubbornly surviving, publishes events then it could be that something unexpected is subscribing to it.

myAlienQueen.LayedAnEgg += Queen_LayedAnEgg;

When you subscribe to an event you are adding yourself as a reference to that event. I.e. in the above you know that the reference count is now at least 1. If you are a good citizen you would also unsubscribe to the event.

myAlienQueen.LayedAnEgg -= Queen_LayedAnEgg;

If you do this you will have left the references at a net count of zero. However, you don’t know who else has subscribed, so you can’t be sure that the reference count is actually 0 as you might expect…or perhaps you can?

Diagnosing the subscription count

Whilst the mechanisms behind the events/multicast delegates are largely hidden from us, we can still view them. E.g. The Alien Queen component could itself list the invocation list;

var subscribers = LayedAnEgg.GetInvocationList();
var count = subscribers.Length;

If the count is more than you expect you could also look at the delegates in the list to see who the delegate belongs to.

That sounds easy enough, but what happens if you have NOT written the object, i.e. you are using the stubbornly alive AlienQueen component but you can’t change its code. Then you can use reflection.

var subscriberCount = GetSubscriberCount(
_myAlienQueen, "LayedAnEgg");

So if you do find yourself with a bad infestation of hard to kill components, you now have one weapon to at least detect if it’s events causing the problem.

--

--