Unity rename public fields to keep assignments

2019-05-10 02:53发布

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.

标签: unity3d
2条回答
Luminary・发光体
2楼-- · 2019-05-10 03:18

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

查看更多
淡お忘
3楼-- · 2019-05-10 03:27

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;
查看更多
登录 后发表回答