Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug The data in the prefab is reset when exiting Unity.

Discussion in 'Scripting' started by OhMyGoat, May 12, 2023.

  1. OhMyGoat

    OhMyGoat

    Joined:
    Jun 16, 2019
    Posts:
    2
    I store the data in a script that is attached to the prefab, everything works fine between the scene on and off sessions, but as soon as I exit the Unity and go back, the value resets to the one set in the inspector..

    Here is the script used on the prefab:
    DWVWEFWEF.png

    And here's what the prefab itself looks like.
    XCXCXC.png

    If I change the values through the inspector, they are saved, but if I change them through the script, they keep their values only until I exit the Unity. Please help solve this
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    If your script is changing the instance of a prefab during runtime (Play mode), that's intended behavior. To really change a prefab, you need to make your script work in edit mode, through AssetDatabase or a similar API.

    All your prefabs and assets are basically protected during the Play mode, prefabs doubly so, because they are only ever instantiated into the scene, so you're already modifying the copy.

    edit:
    If you're talking about the editor script, you need to mark your asset as dirty, and make sure that the internal serialization state acknowledges the modification, but someone else will have to fill you in on the details.
     
    OhMyGoat and angrypenguin like this.
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Adding to the above, if you're using a prefab asset as a form of data container... don't do that; that's not their intended usage. Use scriptable objects instead.
     
    orionsyndrome likes this.
  4. OhMyGoat

    OhMyGoat

    Joined:
    Jun 16, 2019
    Posts:
    2

    I found this solution to my problem, thanks
    Code (CSharp):
    1. using UnityEditor;
    2.  
    3.     public void SaveProgress()
    4.     {
    5.         EditorUtility.SetDirty(prefabScript);
    6.     }
    7.     private void OnApplicationQuit()
    8.     {
    9.         SaveProgress();
    10.     }