【问题标题】:Unity Score does not increase团结分数不增加
【发布时间】:2015-12-19 16:49:16
【问题描述】:
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);
    }
}

而这段代码就是增加分数
我创建了一个画布并想更改属于画布文本的分数 画布文本有scoremanager1 脚本

【问题讨论】:

  • 那么scorevalue 变量的值是多少?您是否进行了一些日志记录,以便您可以看到它明确到达 decrease() 中的 else 语句?
  • 我的初始化是 public int scorevalue=10
  • ScoreManager1.score+=scorevalue;表达式前后放置一个Debug.Log("Score: {1}", ScoreManager1.score);并观察日志。
  • 我解决了我改变了我的 scorevalue 变量的名字 monodevelop 真的很奇怪
  • if 语句中的“else”是否会发生? “current()”的值是多少?

标签: c# unity3d unity5


【解决方案1】:

对于面向对象编程的最佳实践,您不应公开您的分数变量。这是因为您无法控制它可以设置的值。例如;如果您公开了一个公共类并将其值设置为某个值,在大多数情况下,您会希望禁止 null 值,因为对该类的所有后续操作都会返回 NullReferenceException。

但是,对于您想要实现的目标,您可以使用附加了静态方法的类。如下图所示,score 和 text 的值是静态存储的,而 text 的值是在 Awake 上获取的。然后我们使用静态方法 AddScore 来设置 score 的值(将它的值限制为 0 和整数的最大值),然后再设置文本字段的 text 属性。

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 和您需要的任何其他功能添加更多静态方法。

希望这对某些人有所帮助,如果想要稍微不同的方法,您也可以查看static classes versus singletons

【讨论】:

    【解决方案2】:

    您可以使用 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);
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多