Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 ThatBenGuy · Nov 11, 2012 at 10:29 AM · javascriptplayerprefsscore

Issue with PlayerPrefs and local highscore

Hello I'm trying to use PlayerPrefs to save a score and then display it in another scene. I'm basing it off a script from another [question][1], but without the player being able to save their name. However I'm having some trouble getting it to work. If it helps this is my point scoring script, I've named it 'PointScoring': Updated

 private var powerUpAble = true;
 var score = 0;
 var DeductSlowDownScore = 65;
 var scoreText = "Score: ";
 var mySkin : GUISkin;
 var saveScoreScript : SaveScore;
 
 function Start(){
 saveScoreScript = GetComponent(SaveScore);
 }
 
 function OnTriggerEnter( other : Collider ) {
     Debug.Log("OnTriggerEnter() was called");
     if (other.tag == "Coin") {
         Debug.Log("Other object is a coin");
         score += 115;
         Destroy(other.gameObject);
     } 
         else if (other.tag == "Rock") {
         Debug.Log("Other object is a rock");
         score = Mathf.Max(0, score - 75);
     }
          else if (other.tag == "Tree") {
         Debug.Log("Other object is a tree");
         score = Mathf.Max(0, score - 50);
     }
 
     scoreText = "Score: " + score;
     Debug.Log("Score is now " + score);
     saveScoreScript.AddScore(score);
 }
 
 function OnGUI () {
     GUI.skin = mySkin;
     GUI.Box (Rect (140, 10, 500, 200), scoreText.ToString());
     if (powerUpAble)
     if (GUI.Button (Rect (5, 65, 110, 60), "Slow Down"))
         StartCoroutine( SlowDown( 1.5 ) );
  
      }
 
 
 function SlowDown(deactivateInSeconds : float)
 {
     var script4 = GetComponent("Raft Forward - Easy"); 
     script4.enabled = false;
     var script5 = GetComponent("RaftForwardEasier - Easy"); 
     script5.enabled = true;
     var script6 = GetComponent("Pause Button - Easy"); 
     script6.enabled = false;
     powerUpAble = false;
 
     yield WaitForSeconds(deactivateInSeconds);
 
     script5.enabled = false;
     script4.enabled = true;
     script6.enabled = true;
     score = Mathf.Max(0, score - DeductSlowDownScore);
     scoreText = "Score: " + score;
     Debug.Log("Score is now " + score);
     powerUpAble = true;
 
 }; 
     

Here is the script I'm using to save the score, which I've called 'SaveScore': Updated

     GetComponent("PointScoring");
     function AddScore(score : int){
        var newscore : int;
        var oldscore : int;
        newScore = score;
        for(i=0;i<10;i++){
           if(PlayerPrefs.HasKey(i+"HScore")){
              if(PlayerPrefs.GetInt(i+"HScore")<newScore){ 
                 oldScore = PlayerPrefs.GetInt(i+"HScore");
                 PlayerPrefs.SetInt(i+"HScore",newScore);
                 newScore = oldScore;
              }
           }else{
              PlayerPrefs.SetInt(i+"HScore",newScore);
              newScore = 0;
           }
        }
     }
     

Both my point scoring script and the script I'm using to save the score are attached to the same gameobject in the same scene. And lastly this is the script I'm trying to use to display the score in another, seperate scene. I've name it 'DisplayScore':

     var HighestScoreAchieved : int;
     
     function UpdateHScore(){
     
         HighestScoreAchieved = PlayerPrefs.GetInt("0HScore");
     
     }

The problem is that the player's score isn't being recorded. In the scene where I want to display the score the inspector shows 'Highest Score Achieved' as 0, instead of what the score actually was. I'm not sure where I'm going wrong.

Any answers or feedback are greatly appreciated. -Ben [1]: http://answers.unity3d.com/questions/20773/how-do-i-make-a-highscores-board.html

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 Nercoe · Nov 11, 2012 at 10:43 AM 0
Share

Ok so let me get this straight, you just want the high score to be printed to the GameOver screen without a name, just a number??

avatar image ThatBenGuy · Nov 11, 2012 at 10:50 AM 0
Share

Sort of. I'm just trying to get the 'saving and displaying the score part' down pact now and I'll work one some coding to show the score after something like 'Highest Score achieved:...' later.

3 Replies

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

Answer by Seth-Bergman · Nov 11, 2012 at 11:00 AM

you need to call AddScore() in order to send it a score.. Where are you doing that? There are a few weird things here besides:

the first line:

 GetComponent("SaveScore");

instead, we can declare a var of that type.. (use the Start function to initialize it). remove that line, and add these lines to "PointScoring":

 var saveScoreScript : SaveScore;
 
 function Start(){
 saveScoreScript = GetComponent(SaveScore);
 }

... Also, this line:

 print(AddScore);

not sure what that's meant to be.. but it's not even inside any function, so it won't be called at any rate..

To call AddScore, you could add this line to the (updated) PointScoring script:

  ...
 scoreText = "Score: " + score;
 Debug.Log("Score is now " + score);
 saveScoreScript.AddScore(score);    //add this line
 }

so here would be the updated script:

 private var powerUpAble = true;
 var score = 0;
 var DeductSlowDownScore = 65;
 var scoreText = "Score: ";
 var mySkin : GUISkin;
 var saveScoreScript : SaveScore;
 
 function Start(){
 saveScoreScript = GetComponent(SaveScore);
 }
 
 function OnTriggerEnter( other : Collider ) {
     Debug.Log("OnTriggerEnter() was called");
     if (other.tag == "Coin") {
         Debug.Log("Other object is a coin");
         score += 115;
         Destroy(other.gameObject);
     } 
         else if (other.tag == "Rock") {
         Debug.Log("Other object is a rock");
         score = Mathf.Max(0, score - 75);
     }
         else if (other.tag == "Tree") {
         Debug.Log("Other object is a tree");
         score = Mathf.Max(0, score - 50);
     }
 
     scoreText = "Score: " + score;
     Debug.Log("Score is now " + score);
     saveScoreScript.AddScore(score);
 
 }
 ... etc

EDIT:

Update-- The first script is good now, don't mess with it (except you can delete the stray semi-colon at the end)

The SECOND script is still problematic... Let's just try to simplify things:

 GetComponent("PointScoring");  // this line does nothing, delete it!
 function AddScore(score : int){
          if(PlayerPrefs.GetInt("High Score") < score)
             PlayerPrefs.SetInt("High Score",score);
   }


then of course the third script looks like:

 var HighestScoreAchieved : int;

 function Update(){
     HighestScoreAchieved = PlayerPrefs.GetInt("High Score");
 }


simple as that

Comment
Add comment · Show 5 · 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 ThatBenGuy · Nov 16, 2012 at 10:43 PM 0
Share

Thank you for your answer. Still nothing, the HighestScoreAchieved variable in my DisplayScore script still becomes 0. I'm certain I've used your coding, and activated everything, correctly. Are there extra steps that I'm missing out here. Like does my SaveScore script need DontDestroyOnLoad or anything like that? I'm still very new to all this.

avatar image Seth-Bergman · Nov 17, 2012 at 08:33 AM 0
Share

why don't you edit the original post and update it with your current code, that way we can see what's still wrong

avatar image ThatBenGuy · Nov 17, 2012 at 09:05 AM 0
Share

I've updated it now

avatar image Seth-Bergman · Nov 17, 2012 at 09:39 AM 0
Share

$$anonymous$$ let me fix my answer ;)

DONE!

avatar image ThatBenGuy · Nov 17, 2012 at 10:47 AM 0
Share

Thank you very much! All is well. I really appreciate you taking time out to help me :)

avatar image
2

Answer by Nercoe · Nov 11, 2012 at 10:57 AM

You are really making a mountain out of a molehill here buddy! There is a really easy way to do this, I had to do it for a university project and mine scored top marks :) Here's how to do it in less than 10 lines of code.

Step 1: Delete anything you have already included about PlayerPrefs and high scores, let's work with a fresh base.

step 2: Locate the script that enables the Win Game state (maybe if you destroy all the targets the win game scene will be loaded). Once you have done this under the "Application.LoadLevel(winGame)" you need to include this but make it fit your code:

 function GameOver()
 {
         
         if (score > PlayerPrefs.GetInt("HighScore")){
         PlayerPrefs.SetInt("HighScore", score);
                 
         }
                Application.LoadLevel(WinGame);
 }


Basically this is telling the program to save the variable score as HighScore. This will be consistent even if the application is closed. PlayerPrefs are great!

Step 3: Create a final script named anything, I named mine HighScoreDisplay and include this:

 var hScore: TextMesh; //Declares a text mesh
 
 function Awake(){
 
 hScore.text = "High Score: " + PlayerPrefs.GetInt("HighScore");
 }


You'll be glad to know that's all the script it takes to get this working! You need to attatch the latter script to a text mesh in your win game scene. Once you have attached it, drag the text mesh from the hierarchy to the variable slot (HighScoreDisplay) and see what you get!

Let me know how you get on.

Comment
Add comment · Show 3 · 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 ThatBenGuy · Nov 12, 2012 at 12:30 AM 0
Share

Thank you very much. I'm having a little trouble with incorporating your script though. I've created a separate script for the 'function GameOver()' code you provided which is activated when the player reaches the end of the level and the End Game menu pops up. When the player clicks 'Yes', choosing to save their score, the 'function GameOver()' script becomes enabled and the High Score scene is loaded. I still can't seem to get the 'function Gameover()' script to work properly though. The inspector is saying that 'score' in line 4 and 5 is an unknown identifier. I tried adding 'var score: int;' which fixes the problem but the player's score isn't being recorded and displayed.

avatar image Nercoe · Nov 12, 2012 at 12:47 AM 0
Share

This line here:

    if (score > PlayerPrefs.GetInt("HighScore")){

replace it with this:

    if (score < PlayerPrefs.GetInt("HighScore")){

Tell me what happens.

avatar image caleb_b · Jun 29, 2014 at 02:47 AM 0
Share

I know this is kinda old, but I just wanted to say thanks for this answer. I was looking for something like this, and couldn't find anything simple. Your codes are very simple and easy to implement, and work perfectly in my game.

avatar image
1

Answer by neogrant2 · Nov 26, 2012 at 10:45 PM

Adding on to Nercoe, you can do it as gui text aswell.

var scores : GUIText;

 function Awake(){
 
 scores.text = "High Score: " + PlayerPrefs.GetInt("HighScore");
 
 }
Comment
Add comment · 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

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

12 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

Related Questions

Highscoring and changing scripts (Java/UnityScript) 1 Answer

using playerprefs to update a guitext and record highscores 1 Answer

Is there a decent tutorial for a local high score table (android)? 1 Answer

PlayerPrefs not saving my variable value for HighScore System 3 Answers

Guide in ArrayPrefs or PlayerPrefx? 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