- Home /
I want to keep coins and score after player`s death, and also to have high score
Please answer l need you, l am stuck at this topic for about 2 months, if you solve me this problem l can launch my first game, if u do not l dont know where to find answers anymore. Please l am looking forward for your responds.
========================================
This is my script for coins
public class Coin : MonoBehaviour
{
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Marko"))
{
CoinText.coinAmount += 1;
Destroy(gameObject);
}
}
}
And score Manager
public class ScoreManager : MonoBehaviour
{
public int score;
public Text scoreDispaly;
public const string PrefScore = "prefScore";
private void Update()
{
scoreDispaly.text = score.ToString();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle")) {
score++;
Debug.Log(score);
}
}
}
Answer by rh_galaxy · Oct 17, 2020 at 06:48 AM
One way to do this is that you save it to PlayerPrefs before you die, and load it when you respawn.
int iScore = PlayerPrefs.GetInt("MyLastScore", 0);
PlayerPrefs.SetInt("MyLastScore", iScore);
PlayerPrefs.Save();
That's for if you switch scenes after you die and come to life again.
Another way of keeping a value between scenes is to have a GameManager-script that you have on a singleton Do Not Destroy object. And set the score to a variable in that script during scene transitions and put it back to your score after. You can look it up.
Does it save when l exit the game and play again? @rh_galaxy
Thank you man, it is working all fine. You saved my game! Big THANKS!!!
Your answer
Follow this Question
Related Questions
How can i get the following script back on track to being a single level high score saver 0 Answers
saving highscores 1 Answer
Coins store problem !!! 1 Answer
How to save a high score 2 Answers
When should I save data 2 Answers