簡體   English   中英

Unity Score不會增加

[英]Unity Score does not increase

public static int score;        // The player's score.
Text text;                      // Reference to the Text component.
void Awake ()
{
    // Set up the reference.
    text = GetComponent <Text> ();  
    score = 0;
}
void Update ()
{
    // Set the displayed text to be the word "Score" followed by the score value.
    text.text = "Score: " + score;
}

這是分數經理課我需要增加我的分數,但分數總是為零

public void decrease() {
    if (current () > 1)
        tm.text = tm.text.Remove (tm.text.Length - 1);
    else {
        ScoreManager1.score+=scorevalue;
        Destroy (transform.parent.gameObject);
    }
}

而這段代碼就是提高分數
我創建一個畫布,想要改變得分屬於canvas的文本畫布文本有scoremanager1腳本

對於面向對象編程的最佳實踐,您不應公開公開您的分數變量。 這是因為您無法控制可以設置的值。 例如; 如果你公開了一個公共類並且將它的值設置為某些東西,在大多數情況下你會想要禁止null值,因為對該類的所有后續操作都將返回NullReferenceException。

但是,對於您要實現的目標,您可以使用附加了靜態方法的類。 如下所示,分數和文本值是靜態存儲的,文本的值是在Awake上獲得的。 然后,在設置文本字段的text屬性之前,我們使用靜態方法AddScore來設置score的值(將其值鉗位為0和整數的最大值)。

public class ScoreManager : MonoBehaviour
{
    private static  int     m_score;
    private static  Text    m_text;

    public void Awake()
    {
        m_text  = GetComponent<Text>();
        AddScore(0);
    }

    public static void AddScore(int p_score)
    {
        m_score = Mathf.Clamp(m_score + p_score, 0, int.MaxValue);
        m_text.text = "Score: " + m_score;
    }
}

同樣,您可以為SetScore,ResetScore以及您需要的任何其他功能添加更多靜態方法。

希望這能幫助一些人,如果想要一個稍微不同的方法,你也可以看靜態類和單身

您可以使用PlayerPrefs來確保您保存分數。 Playerprefs用於在內部設備中保存數據(字符串,整數等)。 在你的情況下,它應該是這樣的。

  public void Start(){

                PlayerPrefs.SetInt("Score", 0);
                // Set up the reference.
                m_text  = GetComponent<Text>();
                m_score = PlayerPrefs.GetInt("Score",0);
            }
  public static void AddScore(int p_score)
    {

        m_score = Mathf.Clamp(m_score + p_score, 0, int.MaxValue);
        m_text.text = "Score: " + m_score;
        PlayerPrefs.SetInt("Score", m_score);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM