while working with unity I made a simple code that I assume have no problems :
using UnityEngine;
using System.Collections;
public class CardModel : MonoBehaviour {
SpriteRenderer spriteRenderer;
public Sprite[] faces;
public Sprite cardBack;
public int index;
public void toggleCard(bool showFace)
{
if(showFace)
{
spriteRenderer.sprite = faces[index];
}
else
{
spriteRenderer.sprite = cardBack;
}
}
void awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
}
to test the objects and script, I made a test code script along with a gameObject(all this while following a tutorial on youtube) here's the test code :
using UnityEngine;
using System.Collections;
public class DebugCard : MonoBehaviour {
CardModel cardModel;
int index = 0;
public GameObject card;
void awake ()
{
//cardModel = new CardModel ();
cardModel = card.GetComponent<CardModel>();
}
void OnGUI()
{
if(GUI.Button(new Rect(100,50,100,50),"click me !"))
{
cardModel.index = index; //the exception is here !
cardModel.toggleCard (true);
index++;
if (index == 53)
{
index = 0;
cardModel.toggleCard(false);
}
}
}
}
and while running with unity there's no problem... But, each time I press the button(the one with : click me) the console displays :
NullReferenceException: Object reference not set to an instance of an object DebugCard.OnGUI () (at Assets/scripts/DebugCard.cs:20)
I've seen a lot of NullReferenceException problems in stackOverFlow but still coudln't fix it !