Posts Tagged weaktable

.NET 2.0 Unity WeakTable – Store extended variables against anything


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.

This technique will work from Javascript and C#, but the code has to be in C# hence I’ve built it as a plugin unity package you can download from here.

You use it like this (clearly this is an example, I could just modify test!):

//Javascript

//You can have any number of these type of classes
class MyExtendedProperties
{
    //Any number of members
    public var aProperty : String;
}

//This is a test class for this example
//try to believe that it's an object that we've
//got that we can't change the source of
class test
{
    //This is just so that there is something there
    public var test: String = "Hello";
}

function Start () {
    //Create a new instance of test
    var o = new test();
    //Give it an extra property in a new instance of MyExtendedProperties
    Extension.Get.<MyExtendedProperties>(o).aProperty = "World";
    //Read it back
    Debug.Log(Extension.Get.(o).aProperty);

    //Next time the garbage collector runs our extended properties will be cleaned up
    //as nothing has a reference to o
}

The C# is probably pretty obvious from that Javascript apart from the fact that the .Get method is an extension method callable in C# like this

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.

, , ,

Leave a comment