Unity3D: HighScore - unity3d

Okay to be basic, I have a 2d top down game on unity. The premises of my game is to collect as much coins as you can before you die. I used player pref so that when a player get the highest score it will save the person's score. However I am facing a problem, which is; when you first play the game, you collect coins then die, the game then saves the highest point you got and displays it on a panel that comes down, BUT if you play the game again and don't collect any coins, then the game doesn't show the highest point you got, instead it will show "0". So to sum up if I don't collect any coins and I die then the panel will come down and show 0 as my high score. So I have to get at least 1 coin for it to show the person highest high score. Which is not want I want, want I want is for when the player dies, regardless of how many coins you have collected, it will show (in my panel) your highest high score the person got to. Does anyone knows how to fix this??? Thank you.
This is my code:
public Text ScoreText;
public Text Highscoretext;
public AudioClip coinsound;
public int Score;
public int highScore = 0;
void Start ()
{
Score = 0;
SetScoreText ();
if (PlayerPrefs.HasKey ("Highscore"))
{
highScore = PlayerPrefs.GetInt("Highscore");
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
Score = Score + 1;
SetScoreText ();
AudioSource.PlayClipAtPoint (coinsound, transform.position);
}
}
void SetScoreText ()
{
ScoreText.text = "Score: " + Score.ToString ();
Highscoretext.text = "Highscore" + highScore.ToString ();
}
Thank you.

Just use two playerpref variables. "ScoreThisPlaySesssion" and "HighestScoreEver" count score this session up when you collect coins and when that is higher than "highest score ever" count that up with one value evert time you get a coin.
void Start ()
{
Score = 0;
SetScoreText ();
if (PlayerPrefs.HasKey ("Highscore"))
{
highScore = PlayerPrefs.GetInt("Highscore");
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
Score = Score + 1;
SetScoreText ();
AudioSource.PlayClipAtPoint (coinsound, transform.position);
}
}
void SetScoreText ()
{
ScoreText.text = "Score: " + Score.ToString ();
if( PlayerPrefs.GetInt( "highestscoreever", 0 ) < Score )
PlayerPrefs.SetInt( "highestscoreever", Score );
Highscoretext.text = "Highscore" + PlayerPrefs.GetInt( "highestscoreever", 0 );
}

Related

How replay score to 0 using unity?

I have quiz game which is the last game the score is come out.
the score is save and can show when the game is over, but when i replay the game the score don't return to zero
Here is my code in question and answer
public class QuestionAnswer : MonoBehaviour
{
public GameObject feedback_benar, feedback_salah;
public void answer(bool QuestionAnswer){
if (QuestionAnswer) {
feedback_benar.SetActive(false);
feedback_benar.SetActive(true);
int skor = PlayerPrefs.GetInt ("skor") + 10;
PlayerPrefs.SetInt ("skor", skor);
} else{
feedback_salah.SetActive(false);
feedback_salah.SetActive(true);
}
gameObject.SetActive (false);
transform.parent.GetChild(gameObject.transform.GetSiblingIndex()+1).gameObject.SetActive (true);
gameObject.SetActive (true);
}
}
and this in my score script code
public class Skor : MonoBehaviour
{
void Update()
{
GetComponent<Text> ().text = PlayerPrefs.GetInt ("skor").ToString();}}
}
}
If you want the score to reset each time you play the quiz simply don't save it, however if you want to implement a high score system you would do something like this.
private float score;
private void Update()
{
if (QuestionAnswered)
{
//Adds one to score if its right
score++;
}
}
void EndGame()
{
// score only gets saved if it is higher than the previously saved highscore
if (score > PlayerPrefs.GetFloat("HighScore", 0f))
{
PlayerPrefs.SetFloat("HighScore", score);
}
}
Then you simply call the endgame method when you want the game to end and it will compare highscore with score and if score is greater than saved highscore it will get updated.

PlayerPrefs for score in dynamically loaded levels

Im creating a brick breaker game in Unity with one scene called Game that loads every single level based on data received from a json file.
I.E :
Once all bricks are destroyed from 1 level, the second level is
loaded in the same scene, and so on.
Once you lose, a "Lose" scene is loaded with a "Play Again" button.
I'd like the high score information to be retained in the player prefs even after you press the "Play Again" button.
But I'm a bit confused to how this works. This is my code for score:
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Text scoreText;
public Text highScoreText;
private int score;
private int highScore;
void Start()
{
score = 0;
GetHighScore();
}
void Update()
{
UpdateScore();
SetHighScore();
GetHighScore();
}
// TO UPDATE HIGH SCORE
void SetHighScore()
{
if (score > highScore)
{
PlayerPrefs.SetInt("HighScore", score);
}
}
void GetHighScore()
{
highScore = PlayerPrefs.GetInt("HighScore");
highScoreText.text = "High score: " + highScore;
}
// TO UPDATE HIGH SCORE
// TO UPDATE SCORE
public void AddPoints(int points)
{
score = score + points;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "score: " + score;
}
// TO UPDATE SCORE
}
So far the score updates fine, but nothing happens to the high score. Any help is appreciated!
This method here achives nothing
void GetHighScore()
{
PlayerPrefs.GetInt("HighScore");
}
It should be
void GetHighScore()
{
highScore = PlayerPrefs.GetInt("HighScore");
}
And i dont see the point in calling it every frame in Update. Call it once in Start
Also, you may want to update highScore in SetHighScore
if (score > highScore)
{
highScore = score;
PlayerPrefs.SetInt("HighScore", highScore);
highScoreText.text = "high score: " + highScore;
}

Unity2D: Fixing my coin system

The way my coin system works is simple.
The player starts off with 10 fruit automatically
The enemies will then spawn in and steal a random amount of fruit from the player, the amount of fruit the enemy will steal varies from a random integer to the amount the player previously had.
The player can get more fruit by stabbing the enemies, the amount of fruit the player will get varies from a random integer to random integer.
However if the enemy takes a random amount of fruit from the player and then the player then stabs the enemy, the player will get back however much fruit the enemy took from them, plus the an extra bonus of fruit from the enemy (please look at point 3, if needed).
My problem:
This only happens occasionally, but sometimes the coin system will refuse to work especially during the beginning of the game or if the player has a large amount of fruit, i.e. 300 fruits. For example, if the player has about 300 fruits and the enemy takes about 200 fruits from the player (meaning the player will have 100 fruits remanding), then if the player stabs the enemy, the player will only receive about (for example) 25 fruits back instead of the initial 200 + the bonus(for example) 25. As mentioned before, this only happen occasionally - sometimes more than usual however I'd still like to make sure that it works accurately and smoothly. I have tried debugging it, but I am still stuck with why it is not working properly. Can anyone help me fix my codes or give me a better solution as to how I can make a better coin system. Thank you!
Enemy Theft script:
public static int scoreValue;
void Start () {
scoreValue = 0;
}
void Update () {
Debug.Log ("ScoreValue: " + scoreValue);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Farm") {
collidedwithFarm = true;
scoreValue = Random.Range (1, GameController.Fruit);
Debug.Log ("Enemy takes: " + scoreValue);
GameController.Fruit-= scoreValue;
//Wallet += scoreValue;
if (GameController.Fruit<= 0) {
GameController.Fruit = 0;
}
}
}
Enemy's script:
public int randomValue;
public int wallet;
public bool collidedwithFarm = false;
// Use this for initialization
void Start () {
wallet = 0;
collidedwithFarm = false;
randomValue = Random.Range (1, 101);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "playerKnife") {
if (collidedwithFarm == false) {
text.text = " " + randomValue;
Debug.Log ("NOT COLLISION");
GameController.Fruit+= randomValue;
}
else if (collidedwithFarm == true) {
Debug.Log ("COLLISION");
GameController.Fruit+= EnemyTheft.scoreValue+ randomValue;
Debug.Log("Player gets back: " + EnemyTheft.scoreValue);
wallet += EnemyTheft.scoreValue + randomValue;
text.text = " " + wallet;
Debug.Log ("In total: " + wallet);
}
}
}
Coin Script:
public Text FruitText;
public static int Fruit = 10;
void Start()
{
SetFruitText ();
Fruit = 10;
}
void SetFruitText ()
{
FruitText.text = "Fruits: " + Fruit.ToString();
}
You don't need
public bool collidedwithFarm = false;
Remove it and then use this code in EnemyTheft.cs :
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Farm")
{
scoreValue = Random.Range (1, GameController.Fruit);
GameController.Fruit-= scoreValue;
}
}
In Enemy.cs :
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "playerKnife")
{
int payBack = randomValue + EnemyTheft.coinsStolen;
GameController.Fruit += payBack;
wallet -= payBack;
}
}
Hope this helps.

Unity 2d game Coins will reset every game and wont add up to previous coins collected in the previous game any idea?

Code in the character that get the coin and store it the.... coins can display in the start up main.
Example:
I am game over, I earned 40 coins. I clicked play again and I collected 20 coins.
The 20 coins are the only coins that will display in startup main, the previous 40 coins are gone.
function OnTriggerEnter2D( other : Collider2D ) {
if (other.tag == "Coin") {
coins += 1;
PlayerPrefs.SetInt ("Coin", coins);
coinsBegin++;
Destroy(other.gameObject); PlayerPrefs.Save(); } }
function OnGUI () { GUI.Label (Rect (20, 20, 200, 40), "score: " +coins + "");
}
function GameOver(){
if(coins > PlayerPrefs.GetInt("Coin", coins)){ PlayerPrefs.SetInt("Coin", coins); } Application.LoadLevel("main"); }
C#:
void GameOver(){
int currentCoin = PlayerPrefs.GetInt("Coin", 0);
if(currentCoin < 20){
Debug.Log("Not enough coins to play !");
}else{
currentCoin -= 20;
PlayerPrefs.SetInt ("Coin", currentCoin);
Application.LoadLevel("main");
}
}

Incorrect text on screen

Hi I'm new to this unity and I'm making a 2d game the problem.I'm facing is displaying the right text in the screen , e.g I have a score count for keeping track of score and then I'm displaying this text through count.text , HOWEVER the problem is that when the game starts the text on screen displays "0", score is 0 as well, then I shoot an apple and the score becomes 1 as well as the count.text also becomes 1 however the text is still 0 on the screen, when I shoot another arrow the score and count.text shows value of 2 however on the screen it shows 1 and so on. I followed unity tutorial of roll the ball. here is my code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class arrowcounttutorial : MonoBehaviour {
public GameObject Arrow;
public GameObject apple;
public int score = 0;
public Text count;
// Use this for initialization
void Start () {
this.gameObject.GetComponent<Rigidbody2D> ().AddForce (transform.right*1500.0f);
//score = 0;
//showcounttext ();
count.text = score.ToString ();
}
// Update is called once per frame
void Update () {
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 0);
if (Input.GetMouseButtonUp (0)) {
GameObject bullet_new;
bullet_new = Instantiate (Arrow,new Vector2 (-0.23f, -3.78f), Quaternion.identity) as GameObject;
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector2.zero);
if (hit.collider!= null ) {
LeanTween.move(bullet_new, hit.collider.transform.localPosition, 1);
if(hit.collider.tag == "fruit")
{
score++;
//showcounttext();
count.text = score.ToString ();
print(count.text);
Destroy(hit.collider.gameObject,1);
Destroy(bullet_new,1);
}
}
}
}
/*
void showcounttext(){
count.text = score.ToString ();
}
*/
}
Also if I initialize the score in void start the text remains 0 through out the level even if the score and count.text are 1,2,3,4,5 so on. What can I do?
UPDATE
I don't know how it worked but I called an invoke function Invoke ("showcounttext",1); and it worked. I won't delete the question in case someone else have this same problem :)
I see your answer, good that it is fixed but it is not the best solution.
Prior to Unity3D version 5.3.1p3 this engine had problems with updating canvases, and sometimes the UI content was disapearing. You didnt tell version you use, but I am almost sure in this case it would help calling
Canvas.ForceUpdateCanvases ();
In your code it should look like that:
if(hit.collider.tag == "fruit")
{
score++;
//showcounttext();
count.text = score.ToString ();
print(count.text);
Destroy(hit.collider.gameObject,1);
Destroy(bullet_new,1);
Canvas.ForceUpdateCanvases ();
}
Try this, or upgrade Unity3D.