Reputation: 1
I am new to using unity and also coding in C#, the problem I'm having is that when I change the value of a variable inside visual studio the code in the c# script does not update. I am not sure what the problem is I have tried a bunch of different methods but nothing seems to work. The current version of unity I'm using is 2020.1.17.f1 on mac os, and I am using visual
studio 2019. Below you can see an example of my code. In the unity console, the correct output isn't displayed. The variable currentAge
is set to 17
, but the output inside of Unity is 31
.
I am not sure how to fix this issue, if anyone has any ideas I would greatly appreciate the feedback.
Upvotes: -1
Views: 1455
Reputation: 90852
This is no "issue", just a misunderstanding ;)
The field
public int currentAge;
is serialized.
What this means in detail you can read in Script Serialization. In short this means this value is
What you can provide in your code is only a default value until you change it via the Inspector. As soon as you change that field value via the Inspector it will get overwritten with this now serialized value. So the next time you hit Play and this script instance is deserialized from the according asset file the value will be loaded and overwrites any default value you have set in your code.
And of course changing the serialized field value will NOT cause a recompilation of your script. You will not see the change reflected in your script! Which makes totally sense: What should happen if you have multiple instances of this script on different GameObjects all with different values? ;)
Also the other way round: If you change that value later in the code you only change the default value, the one in the Inspector, the serialized one will always overrule it.
There are some(?) IDEs (I only use Rider) which are capable of sniffing into the Unity references and asset values and can tell you with what value certain serialized fields are currently serialized/saved with but usually you can only go by what is either set in the Inspector or in the Unity messages like Awake
, Start
, OnValidate
etc.
Upvotes: 2
Reputation: 57
First of all, if you set a variable in the Inspector, this is a priority and will always remain the one in the inspector, only if you do not change it in Start or Awake. To understand, if you changed the value of the variable to 31 in the inspector, then it will remain 31 even if you change in VS.
Upvotes: 0
Reputation:
this is not bug orsomething, it is because you chnaged the value inside the Unity editor, that updates the value but it doesn't update the value inside Visual Studio
Upvotes: 1