Unity Inspector not updating my Script

public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRb;
    public float jumpForce = 10f;
    public float gravityModifier = 1.0f;
  
    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        Physics.gravity *= gravityModifier;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
    }
}

Hi, I have a problem of unity inspector not updating the values from my script. When I change the values of jumpFloat or gravityModifire on the script, it does not shows on my inspector. But it works when I reimport the script. I don’t know if there is mistake somewhere so that it is not updated automatically. Please help me find solution on updating automatically. It has happened to my other scripts too where the the values are not updated automatically.

I even enabled the auto refresh from the preferences after seeing the thread similar to mine but still no update.

That’s because once you’ve added the script to a component, the serialized values of these fields override any values that you set in the script via field initializers. If you want to change Inspector-exposed fields after adding the component to a game object you need to make the change in the Inspector. The script only provides the default values when there is no serialized data available yet.

For example, if you add this script, then change the value of jumpForce to 20 in the script, this will not be reflected in the Inspector for existing scripts. But it will be used as the default value whenever you add the script as a new component to a game object.

1 Like

Serialized / public fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:

  • what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)

  • what may be saved with the prefab

  • what may be saved with the prefab override(s)/variant(s)

  • what may be saved in the scene and not applied to the prefab

  • what may be changed in the scene and not yet saved to disk

  • what may be changed in OnEnable(), Awake(), Start(), or even later

Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.

Here’s the official discussion: https://blog.unity.com/technology/serialization-in-unity

If you must initialize fields, then do so in the void Reset() method, which ONLY runs in the UnityEditor.

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

https://discussions.unity.com/t/829681/2

https://discussions.unity.com/t/846251/8

To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute