首页 文章

如何从ScoreBoard数组中删除重复项?

提问于
浏览
0
public void CheckForHighScore(){
  finall = PlayerPrefs.GetInt("score");// taking score variable from another script to pass in ScoreBoard

   for (int x = 0; x < highScores.Length; x++){
     if (finall > highScoreValues[x]){ 
       for (int y = highScores.Length - 1; y > x; y--) { //sorting
        highScoreValues[y] = highScoreValues[y - 1];
       }
       highScoreValues[x] = finall;
       DrawScores();
       SaveScore();
       PlayerPrefs.DeleteKey("score");
            break;
        }
    }
}



void DrawScores() { 
    for (int x = 0; x < highScores.Length; x++) {  // just adding score to string
        highScores[x].text = highScoreValues[x].ToString();

    }
}

大家好 . 如何从ScoreBoard数组中删除重复项?我试着把这个代码放在排序循环下面,但实际上没有任何反应 . 我也尝试了其他方法,但它们无法正常工作 . 任何帮助表示赞赏 .


/*for (int j = 1; j < x; j++)
        {
            if (highScoreValues[j] == highScoreValues[x])
                break;
            else
                highScoreValues[x] = finall;
        }*/

2 回答

  • -1

    你可以使用linq . 如果highscore是一个对象,则必须重写Equals和GetHashCode

    public override bool Equals(object obj)
            {
                // Insert the Code to override
            }
            public override int GetHashCode()
            {
                // insert the Code to override
            }
    

    请确保,GetHashCode为每个对象返回一个唯一的整数 . 这样你可以在这里看到更多:Correct way to override Equals() and GetHashCode()

    如果highScore是基元,则不需要覆盖这些方法 .

    在统一了highScore之后,您可以使用:

    var sorted = highScores.OrderByDescending(h => h).Distinct() . ToArray();

  • 0
    List<*Insert type of score here*> cache = new List<*Insert type of score here*>();
    for(int index = 0; index < highScores.Length; ++index)
    {
        if(cache.Contains(highScores[index]))
        {
            highScores.RemoveAt(index);
            --index; // Every time you have to remove an item, it will slot the next item
                     // into that index and subtract 1 from highScores length. Thus you 
                     // will have to decriment the index in order to check the item that 
                     // gets pushed into that index of your highScore Array. You many 
                     // need to check the syntax if highScores is not a List. But 
                     // hopefully this helps :)
        }
        else 
        {
            cache.Add(highScores[index]);
        }
    }
        }
    }
    

相关问题