繁体   English   中英

Unity如何在场景更改后重置分数?

[英]Unity how to reset score after scene change?

当我在场景中完成游戏时,开始新游戏时分数仍然存在:

评分系统.cs

    public GameObject scoreText;

    public static int theScore;

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

定时器.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); 

 }
}

每当场景发生变化时如何重置分数?

首先,您需要创建一个名为 GameManager 的空 GameObject,然后向其添加一个您也称为 GameManager 的脚本。 这样您就可以从任何地方访问您的分数。

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;
}

然后你可以从任何地方调用这些变量并改变它们:

GameManager gm;

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

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

您可以使用

void OnSceneLoaded(Scene scene, LoadSceneMode mode)

如果 GameOver 场景使用某种类型的 GameEngineObject,则在 GameOver 场景中重置保存该变量的 GameObject 中的 Score 变量。

Unity 文档场景管理器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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