For part 2 (see part1) of this article I will focus on the classic problem of Rename Refactoring when using Unity. This article assumes Unity version 5.5.

Let's say we have a class like this:

using UnityEngine;

public class MyTest : MonoBehaviour {
    public string theValue;
}

Let's add this script to an empty game object and let's make a prefab from it. Let's add some value to the theValue field on the prefab.

Let's now assume the value held in this field is not descriptive enough. If we want to rename it, the code will be fine with it and changing with something like Ctrl + R + R in Visual Studio will go without errors. The problem is all our prefabs that have been using this script have effectively changed - they have lost the value held in the previous field and the new field now has a default value, making our old value lost forever. Fortunately, this is not too hard to detect even if you didn't know about it (most people probably did) with using source control methods described on this site. This applies only to fields: class renames are fine as long as you also manually rename the code file.

So, what can we do about this?

There is an attribute in Unity called FormerlySerializedAs which does exactly what we want. In order to preserve the value, we must follow these steps:

1. Decorate the field with the attribute.

2. Rename the field using a system wide rename tool as described above. The code will now look like this (notice the namespace inclusion for the attribute):

using UnityEngine;
using UnityEngine.Serialization;

public class MyTest : MonoBehaviour {
    [FormerlySerializedAs("theValue")]
    public string renamedValue;
}

3. Go to Unity and let it reload assemblies (rotating circle in the bottom-right corner). Make sure to check that the renamed fields in the prefabs have the old value and the new name.

4. Update: Turns out it is NOT possible to remove this attribute without losing data!

The biggest problem is remembering to do this on all serialized fields. Maybe with some future versions of VS Tools For Unity it may be possible to automatically detect such renames and apply the work without the attribute juggling? Another problem is we get only one chance to do this properly. If the rename is performed, and there is no attribute applied when the assembly reload happens, the values are lost forever. So, we should make sure to perform the above mentioned steps in order.


If you're finding this article helpful, consider our asset Dialogical on the Unity Asset store for your game dialogues.