Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity rename public fields to keep assignments

how can I rename a field in a Unity script, but keep it's assignment in the Unity Editor inspector? Say I have

public int x;

I assign "1" to x in the inspctor and then i rename x to y in the script. The assignment will then be lost. Is there a way to keep it?

I'm using Visual Studio.

like image 228
Tavados Avatar asked Oct 27 '25 16:10

Tavados


2 Answers

Doing the following will save the value in the inspector. It can be removed after the scene has been saved again.

[FormerlySerializedAs("x")]
public int y;

Read more about it here and here

like image 154
Fredrik Schön Avatar answered Oct 29 '25 06:10

Fredrik Schön


Some additional information on this that may come handy. Renaming is not the only scenario you will need this. If your encapsulate the field you also need to do this.

public int y;

Encapsulate

[FormerlySerializedAs("x")]
//[FormerlySerializedAs("a")] //-has support for multiple renames.
[SerializeField]
private int x;
like image 27
Thulani Chivandikwa Avatar answered Oct 29 '25 07:10

Thulani Chivandikwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!