Renaming a Field Without Losing the Value in the Inspector - Unity Quick Tip
In this Unity quick tip we're going to look at how we can rename fields in a script without losing the values we have set in the inspector.
You can either watch the video version below or continue reading for written instructions.
We're going to start with a simple scene with a single cube.
The cube has the following script attached which rotates the cube at a specified speed
We’ll set the rotation speed to 90.
When we play the game the cube spins around at the speed we specified.
Let’s stop the game and go back to the script. Let's say we wanted to rename the 'rotationSpeed' field.
We can right click on the field and select rename.
We'll rename it to rotationAmount.
Let's save this and switch back to Unity. If we press play now, the cube doesn't rotate!
This is because renaming the field caused us to lose the value we'd entered in the Inspector. At the moment, Unity has no idea that our rotation amount used to be called rotation speed.
Let's stop the game and set the rotation amount to 100. Now when we press play, the cube rotates again.
In this simple scene it's not the end of the world to enter the value again. But if we had several objects using this script, it could be a real problem.
Let's switch back to the script to see how we can prevent this happening.
So we don't lose the value, we need to tell Unity what this field used to be called. We can do this with the FormerlySerializedAs Attribute.
We need to add a using statement for UnityEngine Serialization.
Before we rename the field again, we'll add the FormerlySerializedAs Attribute to the field, and we'll specify that the field used to be called rotation Amount.
Now we'll rename the field to rotationRate.
Let's save this script and switch back to Unity.
Now we can see that the value hasn't been lost in the Inspector
And if we play the game, the cube will still rotate.
That covers everything for this tip. We hope that you found it useful. Please leave any questions or feedback in the comments below, and don't forget to subscribe to get notified when we publish our next post.