Search Unity

Player Prefs not working as intended

Discussion in 'Scripting' started by EvilRhinoGaming, Apr 19, 2021.

  1. EvilRhinoGaming

    EvilRhinoGaming

    Joined:
    Mar 31, 2021
    Posts:
    4
    When the player first opens my game I want the the PlayerPrefKey "NightPref" to be set to 1, however it is being set to 0 instead. Related Code Provided.
    Code (CSharp):
    1.     public static int nightPlayerIsOn;
    2.  
    3.     private void Awake()
    4.     {
    5.         if(!PlayerPrefs.HasKey("NightPref"))
    6.         {
    7.             PlayerPrefs.SetInt("NightPref", 1);
    8.             PlayerPrefs.Save();
    9.             Debug.Log(PlayerPrefs.GetInt("NighPref"));
    10.         }
    11.         else
    12.         {
    13.             PlayerPrefs.SetInt("NightPref", nightPlayerIsOn);
    14.             PlayerPrefs.Save();
    15.         }
    16.     }
     
  2. EvilRhinoGaming

    EvilRhinoGaming

    Joined:
    Mar 31, 2021
    Posts:
    4
    I may or may not have misspelled NightPref...
     
  3. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    It is possible that when you start it for the second time, the last "NightPref" still exists, and the editor needs to clean up PlayerPrefs manually
    For perspective cameras and the near clipping plane is not equal to 0, I recommend setting the near clipping screen to 0 to reduce trouble
     
    Last edited: Apr 19, 2021
  4. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    This script can add a command in editor to clean playerprefs
    Code (CSharp):
    1. public class Test : UnityEditor.Editor
    2. {
    3. [MenuItem("Engine/Clean Up PlayerPrefs")]
    4. private static void Clear()
    5. {
    6.     PlayerPrefs.DeleteAll();
    7.     Directory.Delete(Application.persistentDataPath, true);
    8.     if (EditorApplication.isPlaying)
    9.     {
    10.         EditorApplication.isPlaying = false;
    11.     }
    12. }
    13. }
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    There is not one developer on this entire planet who should EVER concern themselves with spelling.

    Spelling is for word processors and typists working with human text, not for software engineers working with software... that way lies madness! Madness and dragons.

    When you have a string literal, always use a constant string.

    Here's a fine example for PlayerPrefs specifically.

    Here's an example of simple persistent loading/saving values using PlayerPrefs:

    https://pastebin.com/icJSq5zC

    Useful for a relatively small number of simple values.

    This also gets you away from splattering PlayerPrefs calls all over your codebase willy nilly and then forgetting one when you change how you store your persistent data.