Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question SerializeField default value only updates after reimporting prefab

Discussion in 'Scripting' started by diple, Apr 26, 2024.

  1. diple

    diple

    Joined:
    Aug 9, 2019
    Posts:
    3
    I'm using unity 2021 LTS.

    I understand the following situation is intended.
    1. Create a Monobehaviour script, TestScript.cs
    2. Add a SerializeField variable, [SerializeField] private int testValue = 10;
    3. Attach the script to a prefab, TestPrefab.prefab
    4. Change the default value of testValue to 20
    5. testValue of TestPrefab remains at 10 (in TestPrefab.prefab file, there is 'testValue: 10')

    But I cannot understand the following situation.
    1. Create a Monobehaviour script, TestScript.cs
    2. Attach the script to a prefab, TestPrefab.prefab
    3. Add a SerializeField variable, [SerializeField] private int testValue = 10;
    4. Change the default value of testValue to 20
    5. Double-click TestPrefab, testValue of TestPrefab changed to 20
    6. Add TestPrefab to scene, testValue of TestPrefab remains at 10 (in TestPrefab.prefab file, there is no 'testValue')
    7. Reimport TestPrefab
    8. Add TestPrefab to scene, testValue of TestPrefab changed to 20

    Is this intended behavior?
    Is the only way to update all default values to reimport all assets?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,394
    Probably because the initial inline initialised value gets cached in some way upon the prefab being reserialised for the first time. Even if it's not written to disk yet as the prefab hasn't been dirtied and saved yet. The serialiser sees a value that wasn't present before, and adds the initial value to the in memory instance of the prefab.

    A reimport probably clears this caching, though I bet simply closing and opening the editor would get the same effect.

    If the field hasn't even been written to disk then you can just dirty the prefab somehow to ensure it is.
     
    Last edited: Apr 26, 2024
  3. diple

    diple

    Joined:
    Aug 9, 2019
    Posts:
    3
    Restarting the editor didn't fix the issue.
    Because Unity does not reimport assets when restarted.

    And I found the same issue occurs on the public variable too.
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,394
    There is functionally no difference between public fields and fields decorated with SerializeField.

    And again if the value is not written to disk yet, just ensure it is.