好的,所以我正在尝试创建一个高分系统并在对象中使用一个类的数组,但是出现标题中的错误,告诉我由于某种原因我的对象充满了空变量,这是我的类:
class HighScores
{
public HighScore[] MyScores = new HighScore[5];
protected bool failedRead = false;
private void SortHighScores(string NewName, int NewScore)
{
HighScore[] TmpScores = new HighScore[6];
for (int i = 0; i < 5; i++)
{
TmpScores[i].Name = MyScores[i].Name; // Error Occurs here for `MyScores[i].Name` however in output box both MyScores and TmpScores show null
TmpScores[i].Score = MyScores[i].Score;
}
TmpScores[5].Name = NewName;
TmpScores[5].Score = NewScore;
Array.Sort(TmpScores, delegate(HighScore x, HighScore y) { return x.Score.CompareTo(y.Score); });
Array.Reverse(TmpScores);
MyScores = new HighScore[5];
for (int i = 0; i < 5; i++)
{
MyScores[i].Name = TmpScores[i].Name;
MyScores[i].Score = TmpScores[i].Score;
}
}
}
class HighScore
{
public string Name = "hello world";
public int Score = 0;
}
这里是我初始化一个对象的地方HighScores
:
HighScores GameScores;
protected override void Initialize()
{
base.Initialize();
GameScores = new Highscores();
}
如果我将对象设置为new
?
[编辑]
好的,所以我在 HighScores 类中创建了一个新函数来将 MyScores 对象初始化为新的 HighScore 对象:
public void InitScores()
{
for (int i = 0; i < 5; i++)
{
MyScores[i] = new HighScore();
}
}
在内部调用protected override void Initialize()
(相信大家都熟悉它,它是 XNA 中的标准)。我还在类函数中添加了相同的代码:GameScores.SortHighScores
初始化TmpScores
。
还是一样的错误,还是一样的地方,有什么想法吗?