【问题标题】:List C# (Unity) - can not add float values.List C# (Unity) - 不能添加浮点值。
【发布时间】:2017-03-12 15:22:31
【问题描述】:

我试图在GameView 中显示最好的分数,但我的做法不起作用。

我有一名球员必须避开障碍物,但当他未能避开障碍物时,他将无法再移动并且计分将终止。然后,我想把那个特定的分数添加到我的List

但是,在我的代码中,没有添加分数,因为每当我开始游戏时,我都会收到 "Argument out of range" 错误,如果我运行 Debug.Log,我可以看到我的列表中没有任何项目。

这是我的代码。 (在这段代码中,我只想打印第一个索引上的分数,稍后我会添加if conditions 以获得真正的最佳分数)。您应该主要关注void Start()void Update() 的前几行。

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class ScoreManager : MonoBehaviour {

    private float score = 0.0f;
    private int difficultyLevel = 1;
    private int scoreIncrementor = 1;
    private int maxdifficultyLevel = 10;
    private int scoreToNextLevel = 10;
    private bool isDead = false;
    private List<float> scoreBox;

    public Text scoreText;
    public Text bestScoreText;

    void Start(){
        scoreBox = new List<float> ();
        for(float i = 0; i <= scoreBox.Count; i++)
            bestScoreText.text = ("Best Score:  " + ((int)scoreBox [0]).ToString ());

    }


    void Update () {
        if (isDead) {
            scoreBox.Add (score);
            return;

        }
        if (score >= scoreToNextLevel)
            LevelUp ();
        score += Time.deltaTime;
        scoreText.text = ("Score: " + " "+ ((int)score).ToString ());
    }

    void LevelUp(){
        if (difficultyLevel == maxdifficultyLevel)
            return;

        scoreToNextLevel *= 2;
        difficultyLevel++;

        GetComponent<PlayerMovement> ().SetSpeed (scoreIncrementor);
    }

    public void OnDeath(){
        isDead = true;

    }
}

【问题讨论】:

    标签: c# list unity3d


    【解决方案1】:

    问题在于Start() 方法。

    void Start(){
        scoreBox = new List<float> ();
        for(float i = 0; i <= scoreBox.Count; i++)
            bestScoreText.text = ("Best Score:  " + ((int)scoreBox [0]).ToString ());
    }
    

    您正在创建一个没有元素的新列表,然后您尝试显示结果:但位置 0 处不存在任何元素,因此您会得到 IndexOutOfRange 异常。

    &lt;= 更改为&lt;(请记住,索引从0 开始。但长度从1 开始)并且scoreBox[0] 应该是scoreBox[i]

    另外,我可以问一下,如果您将其转换为int,为什么您将列表设为float

    【讨论】:

    • 老实说,我不知道,我先从 int 开始,但后来为了摆脱错误,我开始改变一切。我马上试试这个
    • 但这应该不会改变任何事情吧?在那种情况下,我只更改了 for 循环条件,而不是第一个索引,我采用它们中的每一个?我仍然应该得到同样的错误。
    • 不,你不会。在进入循环代码之前检查for循环的条件,所以当你创建List时,它有Count等于0,因此i &lt; scoreBox.Count将返回false,你不会执行一次代码.
    • @Seinfeld:如果列表是floatint 确实不重要,那么在float 中有一个列表没有多大意义,如果你曾经存储的只是@ 987654336@。至于循环,如果列表中没有元素,则 for 循环将不会以更改的条件执行。既然要显示最高分,就应该使用scoreBox.Max();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多