每秒减少一个计时器,两个整数都在减少

时间:2016-05-26 11:53:13

标签: c# unity3d unity5

我试图在我的游戏中实施分数系统。我有两个变量,

public int maxScore; 
public int currentScore;

要设置currentScore,我会获得maxScore并将其投入currentScore:

currentScore = maxScore;

因此,如果他开始游戏,玩家拥有最高分数。如果他现在要慢,我会用

减少当前的每秒
IEnumerator CurrentScore()
{
        currentScore -= 1;
        yield return new WaitForSeconds(5); //I'm using 5, because 1 does not equals a second
}

并通过说

来称呼它
StartCoroutine(CurrentScore());

如果我现在看看游戏,那一切看起来很好:

随着游戏开始,两者都在3000:

On start of the Game

如果计时器运行到特定值,则currentScore会减少,但MaxScore会保留。应该如此:

然而,一旦WinScreen PopsUp,两个值都开始迅速减少,而不是只有一个减少:

我有这个脚本附加到文本,显示当前(获得)点和可能点:

using UnityEngine;
using UnityEngine.UI;

public class WinScreenScore : MonoBehaviour {
    //Load the classes
    public GameManager manager;
    //To get our Text
    //public GameObject scoreText;
    Text max;
    Text current;
    //As soon as the Thread awakes, load the Text
    void Awake()
    {
        max = GetComponent<Text>();
        max.text = manager.maxScore.ToString();
    }
    void Update()
    {
        current = GetComponent<Text>();
        current.text = manager.currentScore.ToString();
    }
}

显示当前分数(获得分数)的文本脚本:

关于可能的要点:

我无法弄清楚为什么在显示Winscreen后两个值都会迅速下降。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

WinScreenScore在两个文本对象上运行。 在Update方法中,您将获得Text的组件并将其设置为当前分数。所以对你来说最大分数就是这样。唤醒获取文本组件并将文本设置为游戏管理器的最大分数。然后在更新中,将“同一文本”组件设置为当前分数。基本上,您使用相同的文本组件填充max和current。解决方案:创建包含文本组件的游戏对象的公共引用,然后获取两个单独的文本。该脚本不需要在两个对象上运行。

CodeExample:

public GameManager manager;
public GameObject max, achieved;
Text currentText, maxText;
void Start()
{
    currentText = achieved.GetComponent<Text>();
    maxText = max.GetComponent<Text>();
    maxText.text = manager.maxScore.ToString();
}
//Since the current Score needs to be updated
void FixedUpdate()
{
    currentText.text = manager.currentScore.ToString();
}

现在您可以独立设置当前和最大值。在Update中使用GetComponent也是一个坏主意,因为它操作繁重。尽量只在运行一次的地方使用。