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 DubstepDragon · Aug 19, 2016 at 09:50 PM · playerprefsloadingintintegernot

Issue with PlayerPrefs not loading a value, as well as a bug...

My game uses PlayerPrefs to save and load values for the last played Score and Highscore variables (both integers). So far everything's functional except for one thing: when the scene is changed, i.e. back to the main menu or to the options menu, then back to the main game scene, the game doesn't count up the score the next time it is run; in other words, the score variable doesn't count up until the player dies at least once and refreshes. Well, now that I've explained all of that, here's all my related code to the issue:

The Death() method of my Player Movement script:

     void Death() {
         IsAlive = false;
         PlayerPrefs.SetInt("Score", Score.scoreValue);
         if (Score.scoreValue > PlayerPrefs.GetInt("Highscore")) {
             PlayerPrefs.SetInt("Highscore", Score.scoreValue);
         }
         Instantiate (DeathEffect, this.gameObject.transform.position, Quaternion.identity);
         GameOver gameOver = GameObject.Find("Main Camera").GetComponent<GameOver>();
         gameOver.DisplayGameOverGUI();
         gameOver.gameOverPanel.gameObject.SetActive(true);
         Score score = GameObject.Find("Main Camera").GetComponent<Score>();
         score.scoreText.gameObject.SetActive(false);
     }
 

Score.cs:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 public class Score : MonoBehaviour {
 
     public static int scoreValue;
     public Text scoreText;
 
     void Start() {
         scoreValue = 0;
         InvokeRepeating("CountScore", 1, 0.5f);
     }
 
     void Update() {
         scoreText.text = "Score: " + scoreValue + "\nHighscore: " + PlayerPrefs.GetInt("Highscore");
     }
 
     public void CountScore() {
         if(Movement.IsAlive == true) {
             scoreValue++;
         }
     }
 }
 

GameOver.cs:

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 using System.Collections;
 
 public class GameOver : MonoBehaviour {
 
     public Text gameOverText;
     public GameObject gameOverPanel;
 
     void Start() {
         gameOverPanel.gameObject.SetActive(false);
     }
 
     public void DisplayGameOverGUI() {
         if (!Movement.IsAlive) {
             if(PlayerPrefs.GetInt("Highscore")>=(PlayerPrefs.GetInt("Score"))) {
                 gameOverText.text = "Score: " + Score.scoreValue + "\n Highscore: " + PlayerPrefs.GetInt("Highscore") + "\nYou got " + (PlayerPrefs.GetInt("Highscore") - (PlayerPrefs.GetInt("Score"))) + " lower than your highscore. Pretty close!";
             }
             if (PlayerPrefs.GetInt("Score") >= (PlayerPrefs.GetInt("Highscore"))) {
                 gameOverText.text = "Score: " + Score.scoreValue + "\n Highscore: " + PlayerPrefs.GetInt("Highscore") + "\nYou beat your highscore by " + (PlayerPrefs.GetInt("Score") - (PlayerPrefs.GetInt("Highscore"))) + " points!";
             }
         }
     }
 
     public void PlayAgain() {
         SceneManager.LoadScene("Game");
         Movement.IsAlive = true;
         Score.scoreValue = 0;
     }
 
     public void QuitGame() {
         SceneManager.LoadScene("Menu");
         Score.scoreValue = 0;
     }
 }
 

The Start() method of MenuGUI:

     void Start() {
         scoreText.text = "Latest Score: " + PlayerPrefs.GetInt("Score") + "\nHighscore: " + PlayerPrefs.GetInt("Highscore");
     }


Hopefully that helps illustrate and explain my situation... Thanks in advance ^__^

Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by IsaiahKelly · Aug 20, 2016 at 07:45 PM

You should only set or get PlayerPrefs values at key points during gameplay -- usually at the start and end of the game -- and load those values into "normal" variables for actual use. Accessing PlayerPrefs all the time will only lead to issues.

When changing scenes all objects and their data will be destroyed (unless you assign DontDestroyOnLoad)! So you probably want to save and load this data right before and after changing scenes. or just avoid changing scenes altogether.

I would also only have one class (Score.cs) handle all access to PlayerPrefs to keep things as clear and easy to follow as possible. Something like this:

 using UnityEngine;
 using UnityEngine.UI;
 
 public class Score : MonoBehaviour
 {
     public static int curScore;
     public static int highscore;
     public Text scoreText;
     
     // Called at start of scene.
     void Start()
     {
         highscore = PlayerPrefs.GetInt("Highscore");    // Restore latest highscore value.
 
         Movement.IsAlive = true;    // Maybe you need to reset this?
         InvokeRepeating("CountScore", 1, 0.5f);
     }
 
     // Called when changing scenes, if object not set to DontDestroyOnLoad.
     public void OnDestroy()
     {
         PlayerPrefs.SetInt("Highscore", highscore);     // Save highscore value.
     }
 
     void Update()
     {
         scoreText.text = "Score: " + curScore + "\nHighscore: " + highscore);
     }
 
     public void CountScore()
     {
         if (Movement.IsAlive == true)
         {
             curScore++;
         }
     }
 }

Then just access these variables (curScore, Highscore) from the other scripts, rather than going through PlayerPrefs. I also don't know why you would want to save the current score to PlayerPrefs? Just access the current score from Score.cs directly. The score is also probably not counting up because you forgot to set Movement.IsAlive back to true somewhere.

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 DubstepDragon · Aug 20, 2016 at 09:21 PM 0
Share

Thanks so much, you're a lifesaver! This taught me a lesson as well :)

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

54 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

Related Questions

PlayerPrefs setting to an existing int 0 Answers

Creating a Playerpref score system 1 Answer

Damage script not changing enemy's health integer 1 Answer

Storing in PlayerPref based on timer 1 Answer

Saving with PlayerPrefs? How it works? 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