Search Unity

NullReferenceException: Object reference Error. Please help!

Discussion in '2D' started by d083174, Oct 18, 2020.

  1. d083174

    d083174

    Joined:
    Oct 8, 2020
    Posts:
    11
    I keep getting this blankety-blank error from my code:

    NullReferenceException: Object reference not set to an instance of an object
    Deck+<GetCards>d__2.MoveNext () (at Assets/Scripts/Deck.cs:16)
    DeckView.ShowCards () (at Assets/Scripts/DeckView.cs:24)
    DeckView.Start () (at Assets/Scripts/DeckView.cs:17)

    Can someone look at these two classes and tell me where the exception is and how to fix it? The code works for others, but not me. I swear this is bulls&&&&t!

    DECKVIEW CLASS

    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;
    [RequireComponent(typeof(Deck))]
    public class DeckView : MonoBehaviour
    {
    Deck deck;
    public Vector3 start;
    public float cardOffset;
    public GameObject cardPrefab;
    void Start()
    {
    deck = GetComponent<Deck>();
    ShowCards();
    }
    void ShowCards()
    {
    int cardCount = 0;
    foreach (int i in deck.GetCards())
    {
    float co = cardOffset * cardCount;
    GameObject cardCopy = (GameObject)Instantiate(cardPrefab);
    Vector3 temp = start + new Vector3(co, 0f);
    cardCopy.transform.position = temp;
    cardCount++;

    }
    }

    DECK CLASS
    using System.Collections.Generic;
    using UnityEngine;
    public class Deck : MonoBehaviour
    {
    List<int> cards;
    void Start()
    {
    Shuffle();
    }
    public IEnumerable<int> GetCards()
    {
    foreach (int i in cards) <---- Problem here
    {
    yield return i;
    }
    }
    public void Shuffle()
    {
    if (cards == null)
    {
    cards = new List<int>();
    }
    else
    {
    cards.Clear();
    }
    for (int i = 0; i < 64; 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;
    }
    }
    }
     
  2. Valjuin

    Valjuin

    Joined:
    May 22, 2019
    Posts:
    481