Inspector doesn't show updated values for public variables (ISSUE or IGNORANCE?)
Hi!
I've noticed the inspector is not showing the updated values of public variables in a script. For instance, in my script, the public variable useless is equal to 66:
public int useless = 66;
useless is defined and its value assigned before the Start method of a public class
script is saved
Unity has compiled
No warnings or errors
It's also a sunny day today
BUT, the inspector, show me this:
It's quite annoying since the effective value in-game is 666 and not the updated 66. If I initialize the variable in the start function everything it's fine but I cannot access and modify quickly public variables using the inspector before hitting play... which is not really useful.
.
I already tried:
check auto refresh in edit/preferences/
close/open unity and the script editor
remove and re-attach the script
reset script preset
ancient love spells for enchanting modern technology
I don't know if this is actually a Unity issue or just my ignorance regarding Unity, C#, Compilers, and other magical components but I would really appreciate a feedback from this more-helpful-than- Acetylsalicylic-acid community.
Unity Version: 2018.2.3f1 (free, personal) Script Editor: Microsof Visual Studio (15.8) OS: Windows Eyes: brown
Answer by Johandea · Oct 20, 2018 at 03:44 PM
Any variable that are declared as 'public' gets its value from the editor. So if you want to change it you have to do it in the editor or within a method of a script. Just declaring it with another value will not change it. This is the way that it was designed an not an issue, but it takes some time getting used to. Only declare variables as 'public' if you want to be able to adjust them in the editor during runtime.
To follow up, "Inspector wins" is the only way that makes sense. A main purpose of the Inspector is having the variables easily tweakable, without having to open up the code.
The only use of starting values for public variables is when you add the script to something new, to give an initial inspector value.
Thank you for your answers, very helpful and clear!
Just for sharing... in Start function:
public Type x = ( SpecificConditions(x) && setToDefault ) ? x : defaultValueForX;
Allows me to have some extra control over the values modified by the inspector in my script. x will have the inspector assigned value only if the value assigned satisfies certain conditions (SpecificConditions(x)) and there's no intention of having all values set to their default state (setToDefault); else x will be assigned with its default value.
Right in the Inspector I have something like:
bool setToDefault
so that "inspector wins" yes, but only if it's allowed to... Which is kinda useful
Cheers and thanks again!