0

I am making a simple card game in unity, following a tutorial (I am a beginner at unity), an had a very strange error with a simple IEnumerable. Whenever it is called, it returns an error:

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)

I have looked this error up, and know a fair bit about programming, but I cannot seem to get the hang of why this is happening. What's wrong here?

Here is the iterator in question:

public IEnumerable<int> GetCards(){
    foreach (int i in cards) 
    {
        // DEBUG 
        print (i);

        yield return i;
    }
}

'cards' is of type List, and I am calling it from here:

foreach (int i in deck.GetCards()) {
    // some code
}

Here is my setup code, lines 2-6 should prevent 'cards' from being null. Is there something wrong with this?

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 ());
}

What mistake am I making here?

flumperious
  • 164
  • 1
  • 8
  • Did you look at [this question](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)? Do you understand what being null means? Do you see which object is null in your code? – mason Aug 23 '18 at 15:39
  • `cards` is apparently `null`. –  Aug 23 '18 at 15:41
  • I do, indeed, know what null means, yes. I have no idea why cards might be null, but I'll check – flumperious Aug 23 '18 at 15:55
  • it doesn't like the error not being formatted as code for me. Wouldn't let me save otherwise. Sorry Amy – flumperious Aug 23 '18 at 16:17

0 Answers0