0
\$\begingroup\$

I am trying to make a deck of cards in c# for use in Unity. But when i planned it I didn't think that 'Deck.cs' or 'Card.cs' would need to inherit from Monobehaviour.

I have written 3 classes (one is a Monobehaviour, 'Table.cs'). I thought these would work to make a pack of 52 cards.

I get a null reference exception when I try to access the specific card from the Debug.Log line.

Here are the three classes. (I wonder if I am using the 'new' keyword properly)

(Also Table.cs is the monobehaviour and is attached to a Cube called Table in my game scene. There are no other objects or components in the scene besides the default Light and Camera)

 using UnityEngine;

public class Table : MonoBehaviour
{
Deck deck;

private void Start()
{
    deck = new Deck();
    Debug.Log("card 9 = " + deck.cards[9].value);

}
}

and

public class Deck
{
public Card[] cards;



public Deck()
{
    cards = new Card[52];
    for (int suit = 0; suit < 4; suit++)
    {
        for (int val = 0; val < 14; val++)
        {
            Card c = new Card((Card.Suit)suit, val);
        }
    }
}
}

and

 public class Card
{
public enum Suit { HEARTS = 0, DIAMONDS = 1, SPADES = 2, CLUBS = 3 };
public Suit suit;
public int value;


public Card(Suit Suit, int Value)
{
    suit = Suit;
    value = Value;
}

}

The error i get is this: NullReferenceException: Object reference not set to an instance of an object Table.Start () (at Assets/Scripts/Table.cs:12)

And also I first made Card a struct and that doesn't give me the error, but for some reason all the cards remain as HEARTS and value 0 .

Anybody see what I have done wrong? Any help would be great. Thanks!

\$\endgroup\$
3
\$\begingroup\$

I'm not sure what would lead you to believe this has anything to do with MonoBehaviour or not. You just never actually put any cards in your deck, so of course your deck is full of nulls when you try to read cards from it. (Or full of default(Card)s when using struct, the default being the zero of hearts)

You're missing an assignment to store the card c into your cards array, like this:

public Deck()
{
    cards = new Card[52];

    int index = 0;
    for (int suit = 0; suit < 4; suit++)
    {
        for (int val = 1; val <= 13; val++)
        {
            Card c = new Card((Card.Suit)suit, val);

            cards[index++] = c;
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ thanks for finding this. I took a long break from coding so i am making silly mistakes all over the place lol. And @SeanCarey thanks for the help however the capital S in Suit was just so I could avoid doing 'this.suit = suit'. Thanks again for the help fixing this \$\endgroup\$ – Big T Larrity Jun 10 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.