Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by aminkhosravi007 · Apr 16, 2020 at 02:01 PM · unity 5playerprefssaveload

save unlocked character by Playerprefs

hello. I have a code in which when you click on a button and you have enough coins, it must be unlocked and a piece of wood with price on it that acts like a lock must be disappear. Every thing works fine, but when I restart the game, every thing returns to default. I'm new to unity and I want to use Playerprefs but I don't know how exactly. here is my script;

     using System.Collections;
         using System.Collections.Generic;
         using UnityEngine;
         using UnityEngine.SceneManagement;
         using UnityEngine.UI;
         
         public class MainMenu3 : MonoBehaviour {
         public Button WhitePlane;
         public Button BluePlane;
         public static int character_number;
         
         public GameObject wood1;
         public GameObject wood2;
         
         void Start () {
     
         character_number = PlayerPrefs.GetInt ("Number");
         BluePlane.onClick.AddListener (() => {
         character_number=1;
         if (UIManager2.coin_score>=1) {
         UIManager2.coin_score--;
         wood1.setactive (false);
         
         SceneManager.LoadScene ("Menu2");
                     }
         
                 });
                 
        WhitePlane.onClick.AddListener (() => {
         character_number=2;
         if (UIManager2.coin_score>=2){
                         
         UIManager2.coin_score--;
         UIManager2.coin_score--;
         wood2.setactive(false);
         
         SceneManager.LoadScene ("Menu2");
                                   }
                     });
     void Update () {
     PlayerPrefs.SetInt ("Number", character_number);
     }

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lipisis · Apr 16, 2020 at 04:39 PM 0
Share

You've already posted this didn't you ? Debug "character_number" right at the beginning of Start() and see if it has value you expect it to have (same values as in previous game). Pretty sure it is same value and it's not PlayerPrefs problem as I mentioned in previous thread.

avatar image aminkhosravi007 · Apr 17, 2020 at 06:16 AM 0
Share

I tried something like Debug.Log(character_number) at the beginning of start as you said but I couldn't see anything in console! should I try a different code? @lipisis

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Jasr_88 · Apr 16, 2020 at 06:10 PM

You are on the right path, only that the PlayerPrefs.SetInt ("Number", character number); must be immediately after the value character number is setted, not in the Update loop

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aminkhosravi007 · Apr 17, 2020 at 06:11 AM 0
Share

I already tried that but it didn't work. I put SetInt right after where character_number is set but when I restart the game, the lock still exists and the character is still locked! @Jasr_88

avatar image Jasr_88 · Apr 17, 2020 at 02:49 PM 0
Share

Oh well, thas because you need to store a list of characters unlocked, and show or hide the butons based on that list, something like this:

 // The current player selected
 PlayerPrefs.GetInt ("Number");
 
 // The "list" of the characters unlocked
 // This code must go in your "Unlock Character" Logic
 PlayerPrefs.SetInt("character1Unlocked", [0|1]);
 PlayerPrefs.SetInt("character2Unlocked", [0|1]); 

 bool character1Unlocked = PlayerPrefs.GetInt ("character1Unlocked")==0? false:true;
 bool character2Unlocked = PlayerPrefs.GetInt ("character2Unlocked")==0? false:true;

 // This code must go in you "Show Characters" logic
 if(character1Unlocked){
      // Sentences to show the character1 unlocked...
 } else {
      // Sentences to show the character1 locked...
 }


In your code you never verify if the user has previously unlocked the character, only if have enough coins to buy it. But i bet that the value stored in PlayerPrefs is the right one.

EDIT: Sorry that was my bad, there is no such thing as Get/Set bool on PlayerPrefs you need to do a logic to convert an int flag to a bool

avatar image aminkhosravi007 · Apr 17, 2020 at 06:27 PM 0
Share

Thanks but using your code, Unity shows the message that "Unity can't implicitly convert type "int" to "bool". SetBool can't be identified by unity. could you please put your code in my script? I don't know how to use it! @Jasr_88

avatar image Jasr_88 · Apr 17, 2020 at 06:57 PM 0
Share

$$anonymous$$y code is not a working script, is just for reference. To make your code works try something like this

 void Start () {
         character_number = PlayerPrefs.GetInt ("Number");
 
         bool character1Unlocked = PlayerPrefs.GetInt ("character1Unlocked")==0? false:true;
         bool character2Unlocked = PlayerPrefs.GetInt ("character2Unlocked")==0? false:true;
 
         // Activate or deactivate the buttons (This is what is missing in your original code)
         wood1.setactive (character1Unlocked);
         wood2.setactive (character2Unlocked);
         
 
         BluePlane.onClick.AddListener (() => {
             character_number=1;
             PlayerPrefs.SetInt ("Number", character_number);
             if (UI$$anonymous$$anager2.coin_score>=1) {
                 UI$$anonymous$$anager2.coin_score--;
                 PlayerPrefs.SetInt ("character1Unlocked", 1); // 0 is Locked, 1 is Unlocked....
                 wood1.setactive (false);
                 Scene$$anonymous$$anager.LoadScene ("$$anonymous$$enu2");
             }
         });
          

Also, take into consideration the following: even dough this code works, it still requires some optimization, but for now, it will help you understand the basic use of "PlayerPrefs"

Hope it helps

avatar image
0

Answer by aminkhosravi007 · Apr 18, 2020 at 07:24 AM

Thanks. I now understand that I should have set a boolean for lock/unlock and also for Playerprefs. I really don't know what's wrong! It doesn't work yet! Below is my original script. BluePlane is already unlocked by default and UIManager2.coin_score refers to number of coins to be saved and loaded after buying any item. I thought it might be something wrong with this piece of code but nothing changed after I erased that.

   using System.Collections;
   using System.Collections.Generic;
   using UnityEngine;
   using UnityEngine.SceneManagement;
   using UnityEngine.UI;
             
   public class MainMenu3 : MonoBehaviour {
   public Button WhitePlane;
   public Button BluePlane;
   public static int character_number;
             
   public GameObject wood1;
     
   public bool WhitePlaneUnlocked;

             
   void Start () {
         
   character_number = PlayerPrefs.GetInt ("Number");
   WhitePlaneUnlocked = PlayerPrefs.GetInt ("WhitePlaneUnlocked") == 0 ? false:true;
 
   wood1.SetActive (WhitePlaneUnlocked);
 
             
   BluePlane.onClick.AddListener (() => {
   character_number=1;
   SceneManager.LoadScene ("Menu2");
                         }
             
                     });
   UIManager2.coin_score = PlayerPrefs.GetInt ("Score");        
   WhitePlane.onClick.AddListener (() => {
   character_number=2;
   PlayerPrefs.SetInt ("Number", character_number);
   if (UIManager2.coin_score>=2){
                             
   UIManager2.coin_score-=2;
   PlayerPrefs.SetInt("WhitePlaneUnlocked",1);
   wood1.setactive(false);
             
   SceneManager.LoadScene ("Menu2");
                                       }

                         });
 

As far as I know, if statement for number of coins must be terminated once it's character selected. I thought assigning a variable could be helpful. I tried many ways but none of them worked! I really don't know what to do. @Jasr_88

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aminkhosravi007 · Apr 18, 2020 at 04:17 PM 0
Share

I found [This][1] video really helpful. I had some amazing improvements but still it doesn't work! I worked on it for about 4 hours. for the first time my coins didn't change; second time button interactability changed to false and so on. Could you please take a look at this video? This is my first game. @Jasr_88
[1]: https://www.youtube.com/watch?v=G_I6GxGIB_Y

avatar image
0

Answer by meMUmar · Apr 18, 2020 at 05:24 PM

The problem with your code is that you have not assigned a default value to your PlayerPref. Often PlayerPrefs behaves weird when they are not assigned with a default value. So here is the solution to your problem:

In Start function, just replace

 character_number = PlayerPrefs.GetInt ("Number");

with

 if(!PlayerPrefs.HasKey ("Number")) {
    PlayerPrefs.SetInt ("Number", defaultValue);
 }
 character_number = PlayerPrefs.GetInt ("Number");
 

Replace defaultValue with your desired default value.

Hopefully, this small change will help you solve your problem. Now PlaayerPref will initialize when running for the first time and after that will never show weird behavior.

Note: After applying these changes, Go to Edit and click Clear All PlayerPrefs, and then run the program to test whether changes worked or not.

Enjoy.. !!!! ;)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aminkhosravi007 · Apr 19, 2020 at 07:10 AM 0
Share

Thanks. I tried that but I think it must be my fault! What I want : Once one of the characters is selected, your coins must be decreased according to it's price and when you restart the game and that character is selected again, it must not be locked and your coins must not be decreased either. I followed @Jasr_88 instruction but I don't know really what's wrong! I tried instruction by this video and here is my script;

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Scene$$anonymous$$anagement;
 using UnityEngine.UI;
 using UnityEditor;
 public class $$anonymous$$ain$$anonymous$$enu3 : $$anonymous$$onoBehaviour {
 
     int SceneIndex;
 
     public Button BluePlane;
     public Button WhitePlane;
 
     public GameObject wood;
     public static int character_number;
     public int isPlanesold;
 
 
     // Use this for initialization
     void Start () {
         isPlanesold = PlayerPrefs.GetInt ("isPlanesold");
         if (!PlayerPrefs.HasKey ("Number")) {
             PlayerPrefs.SetInt ("Number", 1);
         }
                 character_number = PlayerPrefs.GetInt ("Number");
         UI$$anonymous$$anager2.coin_score = PlayerPrefs.GetInt ("Score");
             SceneIndex = Scene$$anonymous$$anager.GetActiveScene ().buildIndex;
     }
 
     public void Blueplane () {
         character_number = 1;
         Scene$$anonymous$$anager.LoadScene ("$$anonymous$$enu2");
     }
 
     public void BuyWhitePlane () {
         if (UI$$anonymous$$anager2.coin_score >= 1 && isPlanesold ==0) {
             WhitePlane.interactable = true;
             PlayerPrefs.SetInt ("isPlanesold", 1);
             character_number = 2;
             UI$$anonymous$$anager2.coin_score--;
             wood.SetActive (false);
             PlayerPrefs.SetInt ("Score", UI$$anonymous$$anager2.coin_score);
             PlayerPrefs.SetInt ("Number", character_number);
             Scene$$anonymous$$anager.LoadScene ("$$anonymous$$enu2");
         }
         else
             WhitePlane.interactable = false;
     }
 
         void Update () {
         if (Input.GetKeyDown (KeyCode.Escape))
             Scene$$anonymous$$anager.LoadScene (SceneIndex - 1);
         }

it's okay. when for example I earn 1 coin by BluePlane that's already unlocked by default and click on WhitePlane button, it works fine but when I restart the game, the button returns to WhitePlane.interactable = false; I know what should I do but I really don't know how! @me$$anonymous$$Umar

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

229 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Playerprefs to save unlocked button 2 Answers

Saving character selection 1 Answer

PlayerPrefs for FPS? 1 Answer

Coding help: How to use xml serialization 1 Answer

Save/Load Variable with playerprefs 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges