How do you rename a public variable and keep object references/values?

Whenever I rename a public variable, I lose all values/references of that variable in all objects with that component.

What’s the unity way to rename public variables? I guess it’s not with the IDE (unless monodevelop doesn’t have this problem, I’m using visual studio).

2 Likes

Lol thanks, that WOULD fix the issue, but I don't want to use properties for every variable just so I can rename them later.. There must be a proper way to do this in unity. I'd be very surprised if there wasn't.. (If not I'd rather try writing an editor script for it before resorting to using properties for everything.)

–

1 Answer

1

I found a solution that’s still quite tedious for simply renaming a variable but for as often as one needs to rename a variable it’s worth it and works perfectly.

I found the attribute [FormerlySerializedAs(“yourVariablesPreviousName”)] in the UnityEngine.Serialization namespace.

  1. Place the attribute before the variable you wish to rename.

  2. Rename the variable and save changes.

  3. Switch to the inspector, wait for the name to change, it will have reserialized with the new name and keep all values and references.

  4. Remove the attribute (probably optional).

1 Like

Man that is SOOO awesome. I would never have believed there exists an answer. Jesus that is so fricking usefull, thanks A LOT!

–

Perfect !!! Absolute genius.

–

Worked like a charm. Thank you!

–

Hmm, didn't work with me in 2019.3.10.

–

For reference https://blog.unity.com/technology/renaming-serialized-fields

–