in my game the player have to collect a coins. The problem is that when player dies and starts a new game, the number of coins is not reset. For example:
starting new game and collectiong 15 coins, then dies
starting new game and number of coins i set to 15, not 0
How can I fix that??
Script used for displaying score on the screen:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
Coin coin;
void Update()
{
coin = FindObjectOfType<Coin>();
GetComponent<Text>().text = coin.GetScore().ToString();
}
Script used for adding coins to score:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
float speed = 10f;
public static int score = 0;
void Update()
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
private void OnTriggerEnter2D(Collider2D collision)
{
score += 1;
}
public int GetScore()
{
return score;
}
}
I also need to say that I was messin around with PlayerPrefs with that score to make some highscore concept, but I deleted every PlayerPrefs I did. Thanks a lot.
This is the problematic line:
public static int score = 0;
A variable declared "static" will last for as long as the runtime does, even if the object it's tied to is destroyed (it's a value shared across all coin objects).
Ideally, you'd make it non-static (which is what Unity expects).
public int score = 0;
If you then re-create the Coin object whenever the player dies, unity will handle the cleanup for you.
Alternatively, you could add a "Reset" method to the Coin class...
public int GetScore()
{
return score;
}
public void Reset()
{
score = 0;
}
I answered a question which goes into statics in more detail and may be of interest.
Normally when a class has variables, every time you make a new instance of the class, it gets its own copies of each variable.
(You can create two
Animalclasses and give each one a differentName)A
staticvariable is different. Instead of each instance having its own copy of the variable, they all share the same one.So if you set
animal1.StaticName, you'd changeanimal2.StaticNameas well. More to the point, you don't even need to make an animal, you can just setAnimal.StaticNamedirectly.So... A static variable can be read/set (and static methods can be executed) even if you haven't created an instance of the class.
Oh and... If you do decide to keep the score static, you don't need to find a specific object to get the score...
void Update()
{
GetComponent<Text>().text = Coin.score.ToString();
}