Hi there,
I am making a card game and I wanted to deal the deck. Here is my code:
using System.Collections.Generic;
using UnityEngine;
public class Dealer : MonoBehaviour
{
GameObject player1, player2, player3, player4;
public List<GameObject> deck;
// Use this for initialization
void Start()
{
player1 = Instantiate(Resources.Load<GameObject>("Prefabs/Player"));
player2 = Instantiate(Resources.Load<GameObject>("Prefabs/Player"));
player3 = Instantiate(Resources.Load<GameObject>("Prefabs/Player"));
player4 = Instantiate(Resources.Load<GameObject>("Prefabs/Player"));
deck = new List<GameObject>();
FillDeck(); //I deleted this from, unimportant for now
DealDeck();
}
void DealDeck()
{
Player p1 = player1.GetComponent<Player>();
Player p2 = player2.GetComponent<Player>();
Player p3 = player3.GetComponent<Player>();
Player p4 = player4.GetComponent<Player>();
while (deck.Count > 0)
{
int index = Random.Range(0, deck.Count);
GameObject card = deck[index];
deck.RemoveAt(index);
if (p1.Count() < p2.Count())
p1.AddToHand(card);
else if (p2.Count() < p3.Count())
p2.AddToHand(card);
else if (p3.Count() < p4.Count())
p3.AddToHand(card);
else
p4.AddToHand(card);
}
Debug.Log(p1.Count());
Debug.Log(p2.Count());
Debug.Log(p3.Count());
Debug.Log(p4.Count());
}
}
And here is my code for Player:
using UnityEngine;
using System.Collections.Generic;
public class Player : MonoBehaviour {
List<GameObject> hand;
// Use this for initialization
void Start ()
{
hand = new List<GameObject>();
}
public int Count()
{
return hand.Count;
}
public void AddToHand(GameObject card)
{
hand.Add(card);
hand.Sort();
Instantiate(card, transform);
}
}
I get the following error:
NullReferenceException: Object reference not set to an instance of an object
Player.Count () (at Assets/Scripts/Player.cs: 14)
Can someone explain me why this doesn’t work?
Kind regards,
Alex