Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Clearing playerprefs not working in window game build

Discussion in 'Editor & General Support' started by Kas_, Jun 8, 2023.

  1. Kas_

    Kas_

    Joined:
    Dec 27, 2017
    Posts:
    71
    When i create a windows game build and try clicking a button I setup ingame to clear playerprefs it does not clear my playerprefs. Do I need to setup something special to get this to work correctly on windows? If i click the button in editor play mode it will clear my playerprefs settings.

    here's the code i am using
    Code (CSharp):
    1.     public void ClearPrefs()
    2.     {
    3.         foreach (string file in Directory.GetFiles(Application.persistentDataPath))
    4.         {
    5.             try
    6.             {
    7.                 File.Delete(file);
    8.             }
    9.             catch { }
    10.         }
    11.  
    12.         PlayerPrefs.DeleteAll();
    13.         PlayerPrefs.Save();
    14.     }
    Not sure if I need to reference the exact save file? I would only like it to delete certain save files, since there will be 3 save files present in the future.
    Code (CSharp):
    1.     public void SaveData()
    2.     {
    3.         //Save slot
    4.         PlayerPrefs.SetInt("Slot0", 0);
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    First find if the code is even running. Use Debug.Log() and check the runtime device logs.

    If it is running, perhaps there's a permissions problem inhibiting removal of entries in the registry hive, which is (unfortunately) where PlayerPrefs are stored on Windows.

    If that's the actual problem, you can trivially turn your PlayerPrefs code into something that you control that streams to a file, using something like this:

    If you want to use PlayerPrefs to save your game, it's always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

    https://gist.github.com/kurtdekker/7db0500da01c3eb2a7ac8040198ce7f6
     
  3. Kas_

    Kas_

    Joined:
    Dec 27, 2017
    Posts:
    71
    I believe it is a permissions issue, I will give your code a try