I talk a lot about the [SerializeField] attribute. It’s one of the things I like to beat into new Unity developers to keep them encapsulating their code. Being able to assign values or references to fields in the Unity editor is one of the great things about the engine. But if you’re refactoring often enough, you’re bound to come across a situation where you need to re-name a field. If you just jump in and re-name the field though, you’re gonna break things.
Why will renaming break stuff?
Let’s take a look at a scene that I’ve saved (I set serialization mode to “Force Text” so we can read it)
I have a simple scene with an object that contains two serialized fields.
One’s a float, the other is a reference to the camera in the scene.
Here’s the code for that example script.
Let’s see what that ExampleScript data looks like when it’s serialized into the scene file.
The last two fields show the data for this example script.
We have a floatValue set to 5 and a cameraReference for the camera.
Now, if I rename the fields like this.
When the editor tries to find the values for these new fields, they won’t match and we get this.
Because our fields are serialized with different names, there’s no way for the editor to know we want it to preserve those values.
UNLESS we use the attribute [FormerlySerializedAs].
This attribute tells the editor that we want it to look for the current name first, but if that’s not found, look for the former name.
If the new name isn’t found, but the former one is, the editor will pull in the old value then re-serialize it with the new name.
Removing the attribute?
Once you’ve re-named your field, and re-saved every object using that (scenes, prefabs, scriptedObjects), you can remove the attribute. Unless it really bothers you though, I haven’t seen any actual reason it needs to be done. If you decide to do it though, just make sure you’ve committed everything to sourcecontrol first so you don’t lose anything.