Search Unity

Question PlayerPrefs autosave

Discussion in 'Scripting' started by xtdiwd, Mar 24, 2021.

  1. xtdiwd

    xtdiwd

    Joined:
    Jul 25, 2020
    Posts:
    135
    Until Unity 2019 to permanently store (in regedit) the PlayerPrefs I had to call the Save method.
    Now, in Unity 2020 I realized that the values are stored by themselves when I reload the scene, when I would like them to be stored only when I call the Save method.
    How do I restore the original behavior?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    I don't think PlayerPrefs changed. But if you need half-saved states, then just put all the changes in your own data structures and write them to a file (or PlayerPrefs) when you actually DO want them to be saved. That way you're not beholden to undocumented behavior changes in the underlying API.
     
    Brathnann and Joe-Censored like this.
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    The oldest and newest versions of these docs both say that PlayerPrefs are saved automatically when the application quits, and calling Save just forces them to be saved earlier.

    It's possible that previously you were exiting in some uncontrolled fashion where Unity didn't have time to save them.

    It's also possible that Unity has gotten "safer" about saving them, so that some way of exiting that previous bypassed the save no longer does.

    But the basic philosophy is that anything you put into PlayerPrefs is supposed to be immediately permanent, and if Unity fails to save it that's only because something "unexpected" happened to prevent the save. Calling Save explicitly is just a safeguard.
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    It is not unusual for Unity to make minor functional changes to a feature and fail to immediately update the documentation. No idea if this is the case here.
     
  6. xtdiwd

    xtdiwd

    Joined:
    Jul 25, 2020
    Posts:
    135
    You are right: thinking back I never had this problem because I always saved PlayerPrefs.
    Is there any way to save data only through the Save method?
    Without having to use a data structure.
     
  7. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
  8. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    When you call SetString(), users typically want it persisted and saved at that time. Are you implying you want multiple Set functions that temporarily hold the updates, then commit only upon Save? You would have inconsistencies if you called GetString before Save. As @Antistone mentioned, Save is more of a safeguard.

    https://docs.unity3d.com/ScriptReference/PlayerPrefs.SetString.html
     
    Joe-Censored likes this.