简体   繁体   中英

Unity how to reset score after scene change?

When I get my game over the scene the score still remains when a start a new game:

ScoringSYstem.cs

    public GameObject scoreText;

    public static int theScore;

    void Update()
    {   
        scoreText.GetComponent<Text>().text = "Score: " + theScore; 
    }

Timer.cs

   public string LevelToLoad;
 public static float timer1 = 30f;
 private Text timerSeconds;

    public GameObject scoreText;

    public static int theScore;


 // Use this for initialization
 void Start () 
 {
  timerSeconds = GetComponent<Text> ();
 }
 
 // Update is called once per frame
 void Update () 
 {
  timer1 -= Time.deltaTime;
  timerSeconds.text = timer1.ToString("f0");
  if (timer1 <= 0) 
     {    
        timer1 = 30f;    
        Application.LoadLevel (LevelToLoad); 

 }
}

How does it in order to reset the score whenever a scene changes?

First of all you need to create an empty GameObject that you call GameManager then you add a Script to it that you call GameManager as well. So that you can acces your Score from everywhere.

public int score = 0;
public static int time = 30;   

#region Singelton
public static GameManager instance;

void Awake()
{
   if (instance != null)
   {
      Debug.LogWarning("More than one Instance of Inventory found");
      return;
   }

   instance = this;
}
#endregion

public void GameOver()
{
   score = 0;
   scoreText.GetComponent<Text>().text = "Score: " + gm.score;
}

Then you can call theese variables from everywhere and change them as well:

GameManager gm;

void Start()
{
   gm = GameManager.instance;
}

void Update()
{
   if (time >= 0)
      gm.GameOver();
}

You may use the

void OnSceneLoaded(Scene scene, LoadSceneMode mode)

method in your gameover scene to reset theScore variable in your GameObject that holds the variable, if the GameOver scene using a GameEngineObject of some kind.

Unity Doc SceneManager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM