Sometimes you need to store variables next to something that you don’t own! This happens quite a lot in Unity, especially when working with things like NetworkPlayer – you want to associate something with an instance, but you don’t control the lifetime of that instance. Or you want to associate something with a GameObject, but you don’t want to add a script.
In .NET 4 you get support for this stuff already, using a WeakTable – a kind of dictionary that has elements whose lifetime is controlled by the lifetime of the items they reference. .NET 2 doesn’t have this built in by default – but I’ve written a replacement.
You use it like this (clearly this is an example, I could just modify test!):
anythingAtAll.Get<MyExtendedProperties>().aProperty = "cool huh";
So the basic idea it to have a dictionary, keyed off the object that contains another class that you can put extra information in. The problem of just doing this straight off is that the fact that the object is the key will keep the object alive forever – read massive memory leaks if this gets used too widely. The answer to that is to use weak references and get a notification when the garbage collector runs to enable you to clean up the extra instances associated with objects that have been killed.