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

Playerprefs doesn’t work

Discussion in 'Scripting' started by alexandermss2006, Oct 6, 2019.

Thread Status:
Not open for further replies.
  1. alexandermss2006

    alexandermss2006

    Joined:
    Oct 3, 2019
    Posts:
    25
    Hi
    I can't get my code to work
    This is my Save script its applied to My main menu:
    Code (CSharp):
    1. public void OnEnable() {
    2. StartIt.Progress1 = PlayerPrefs.GetInt("MyProgress");
    3. }
    4. public void OnDisable() {
    5. PlayerPrefs.SetInt("MyProgress", StartIt.Progress1);
    6. }
    It doesn't works
    Thanks
     
  2. shawndingo

    shawndingo

    Joined:
    Oct 4, 2018
    Posts:
    83
    Are you getting an error? What is StartIt.Progress1 referring to? Try and use code tag like this..

    Code (CSharp):
    1. public void OnEnable() {
    2. StartIt.Progress1 = PlayerPrefs.GetInt("MyProgress");
    3. }
    4. public void OnDisable() {
    5. PlayerPrefs.SetInt("MyProgress", StartIt.Progress1);
    6. }
     
  3. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    When you are setting PlayerPrefs, you are only changing the cached version. Unless you exit the app through OnApplicationQuit(), you also need to save the preferences:

    Use

    PlayerPrefs.Save();

    for that.
     
    Joe-Censored, Ryiah and shawndingo like this.
  4. shawndingo

    shawndingo

    Joined:
    Oct 4, 2018
    Posts:
    83
    Another save option is Binary Format. I use this with everything. Especially for scores, gold, etc.. Its better for games that you dont want anyone cheating or being able to edit any files like gold. Here are the scripts i use.

    Game.cs This will hold your variables like ints, bools, etc

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [System.Serializable]
    6.  
    7.  
    8.  
    9.  
    10. public class Game
    11. {
    12.  
    13.     public static Game current = new Game();
    14.     public bool aRandomBool;
    15.     public float aRandomFloat;
    16.     public int aRandomInt;
    17.  
    18. }
    SaveLoad.cs This will store your bools, ints, etc in a binary formatted file.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Runtime.Serialization.Formatters.Binary;
    3. using System.IO;
    4.  
    5. public static class SaveLoad
    6. {
    7.  
    8.     public static void SaveGame()
    9.     {
    10.         BinaryFormatter bf = new BinaryFormatter();
    11.         if (File.Exists(Application.persistentDataPath + "/SavedGame.dat"))
    12.         {
    13.  
    14.             FileStream file = File.Open(Application.persistentDataPath + "/SavedGame.dat", FileMode.Open);
    15.             Game game = new Game();
    16.  
    17.          
    18.             game.aRandomBool = Game.current.aRandomBool;
    19.             game.aRandomFloat = Game.current.aRandomFloat;
    20.             game.aRandomInt= Game.current.aRandomInt;
    21.          
    22.  
    23.  
    24.             bf.Serialize(file, Game.current);
    25.             file.Close();
    26.         }
    27.         else
    28.         {
    29.  
    30.             FileStream file = File.Create(Application.persistentDataPath + "/SavedGame.dat");
    31.             Game game = new Game();
    32.  
    33.             game.aRandomBool = Game.current.aRandomBool;
    34.             game.aRandomFloat = Game.current.aRandomFloat;
    35.             game.aRandomInt= Game.current.aRandomInt;
    36.  
    37.             bf.Serialize(file, Game.current);
    38.         }
    39.  
    40.  
    41.     }
    42.  
    43.     public static void LoadGame()
    44.     {
    45.         if (File.Exists(Application.persistentDataPath + "/SavedGame.dat"))
    46.         {
    47.             BinaryFormatter bf = new BinaryFormatter();
    48.             FileStream file = File.Open(Application.persistentDataPath + "/SavedGame.dat", FileMode.Open);
    49.             Game game = (Game)bf.Deserialize(file);
    50.             file.Close();
    51.  
    52.  
    53.             Game.current.aRandomBool= game.aRandomBool;
    54.             Game.current.aRandomFloat= game.aRandomFloat;
    55.             Game.current.aRandomInt= game.aRandomInt;
    56.  
    57.             Debug.Log("Loaded The File");
    58.         }
    59.         else
    60.         {
    61.             Debug.Log("File Does Not Exist");
    62.         }
    63.     }
    64. }

    Then when you want to save, lets say a score, youll call

    Code (CSharp):
    1. Game.current.aRandomFloat += yourScore;
    And when you want to save it after your added yourScore to the Game.current.aRandomFloat you call..

    Code (CSharp):
    1. SaveLoad.SaveGame();
    And at the start of your game/app you want to call Load Function. Only Once!

    Code (CSharp):
    1. SaveLoad.LoadGame();

    And any time you reference your bool, int, float you call something like this.

    Code (CSharp):
    1. Game.current.aRandomFloat;
    2.  
    3. Game.current.aRandomBool;
    4.  
    5. Game.current.aRandomInt;
     
    patrick_Drake likes this.
  5. alexandermss2006

    alexandermss2006

    Joined:
    Oct 3, 2019
    Posts:
    25
    Thanks for the help
    My playerprefs still doesn't work, but is it possible to use binary foramt if i making a webgl game?
     
  6. shawndingo

    shawndingo

    Joined:
    Oct 4, 2018
    Posts:
    83
    Not sure. I would assume so? Im not to acquainted with WebGl.. so i couldn't say for sure but i wouldn't see any reason why not too. Playerprefs saves as a file. Its very easy to cheat with. People can edit your files. But not with binary formater.
     
  7. alexandermss2006

    alexandermss2006

    Joined:
    Oct 3, 2019
    Posts:
    25
    Ok
    My playerprefs worked good, until i used a deletekey function for my progress variable, can that be the problem?
     
  8. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    WebGL has a lot of limitations. There is no file structure and playerprefs I have found are hit or miss. You'll have to be careful when trying to save data for webgl. I found backend services work the best, even if you just using an anonymous account setting (but even this can run into issues).
     
  9. alexandermss2006

    alexandermss2006

    Joined:
    Oct 3, 2019
    Posts:
    25
    Ok, which backend services?
     
  10. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    If you don't need much, playfab has a free tier that allows for unlimited users. It has a few limitations in place, but should work for most people unless you need to store a huge amount of data.
     
  11. JavierOlvera

    JavierOlvera

    Joined:
    Sep 10, 2019
    Posts:
    11
    I have the same problem and I just discovered that PlayerPrefs is not working on OnEnable(), it just works for me on Start() or Update()... I guess it might be related with the Order Of Execution of Unity. I hope this helps! :)
     
  12. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Please don't necro-post with incorrect information.

    PlayerPrefs works in all normal script locations including OnEnable().

    Whatever leads you to conclude otherwise is either your own buggy code, or you are misinterpreting the results.



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

    https://gist.github.com/kurtdekker/01da815d2dfd336a925ae38019c3a163

    Useful for a relatively small number of simple values.




    Here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html




    If you have a new question, make a new post. It's FREE!!




    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?



    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - ONLY post the relevant code, and then refer to it in your discussion.
     
Thread Status:
Not open for further replies.