Skip to main content

Renaming Class / Type Without Breaking Data

You may be familiar already with Unity's [FormerlySerializedAs("oldName")] attribute that can be used in a field declaration to rename it without losing its serialized value. But it's only used for fields, and not for classes/types.

Normally, the serialization system will reset our serialized field data when its class/type is renamed, because it fails to find the type that holds the data structure. This includes renaming or moving the script into a different assembly definition.

However, it's very possible to rename them with a little bit of attention and care, thanks to Odin's serialization system.

Renaming classes / types can be done using the BindTypeNameToType attribute, specifying the old type name, and the new type.

[assembly: BindTypeNameToType("MyOldNamespace.MyOldTypeName", typeof(MyNewNamespace.MyNewTypeName))]

namespace MyNewNamespace
{
public class MyNewTypeName
{
...
}
}

The parameter for the old type name is in string, because obviously the previous type has been renamed and no longer exists as a Type object. The full path of the namespace should also be included.

The second parameter is specified using its Type object.

caution

Make sure to add the BindTypeNameToType along during the type renaming before compiling it, because it will be too late if we bind the type name after the data has been reset.