按照一个教程(我是unity的初学者),我正在统一制作一个简单的纸牌游戏,一个简单的IEnumerable发生了一个非常奇怪的错误。每当调用它时,它都会返回一个错误:
NullReferenceException: Object reference not set to an instance of an object
Deck+<GetCards>c__Iterator0.MoveNext () (at Assets/Scripts/Deck.cs:11)
DeckView.ShowCards () (at Assets/Scripts/DeckView.cs:21)
DeckView.Start () (at Assets/Scripts/DeckView.cs:16)
我已经检查了这个错误,并且对编程有一些了解,但是我似乎无法理解为什么会发生这种情况。怎么了?
这是有问题的迭代器:
public IEnumerable<int> GetCards(){
foreach (int i in cards)
{
// DEBUG
print (i);
yield return i;
}
}
'cards'的类型为List,我从这里调用它:
foreach (int i in deck.GetCards()) {
// some code
}
这是我的设置代码,第2-6行应防止“ cards”为空。这有什么问题吗?
public void Shuffle (){
if (cards == null) {
cards = new List<int> ();
} else {
cards.Clear ();
}
for (int i = 0; i < 40; i++) {
cards.Add (i);
}
int n = cards.Count;
while (n > 1) {
n--;
int k = Random.Range (0, n + 1);
int temp = cards [k];
cards [k] = cards [n];
cards [n] = temp;
}
}
void Start () {
Shuffle ();
print (GetCards ());
}
我在这里犯什么错误?