constants not being processed correctly

I am seeing a problem when I declare a public constant such as

public float min_clearance = 0.002f;

when declared the first time this is correctly populated into the inspector and can then be read by other scripts.

However if I then change this to be say

public float min_clearance = 0.005f;

and save the script, the new value is not copied/updated in the inspector and other classes which read this constant get given the old value rather than the new value.:(.

Is there something else I need to do?

If you do not want to edit it in the inspector than add [NonSerialized].

[NonSerialized]
public float min_clearance = 0.002f;

Or switch from public to private if you don’t need to access it outside of the class.

If you want to edit the value in the inspector, then just edit the value in the inspector. :slight_smile:

1 Like

You’re initializing a field, this way to set values will happen only one time before the constructor, when you add this script as a component in some object unity will construct your class and your fields will be initialized, any time after this point your field initializer will have no effect on the current field value. This will update if you re-add a component or press reset in the component context

1 Like
public float min_clearance = 0.002f;

That is not a constant at all. It’s just a normal variable (and as the name implies the value may change). If you want a constant use:

public const float min_clearance = 0.002f;
1 Like

Adding to the solid basic info from Lurk, Nefisto and exig above, I offer you these further links:

Field initializers versus using Reset() function and Unity serialization:

1 Like