0

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 !

kimovic
  • 33
  • 10
  • Did you add the `CardModel` script to the `card` GameObject? – Keiwan Dec 30 '16 at 12:48
  • I suspect this could be due to `CardModel` may not be instantiating. Did you try debugging a break point? Also please write a comment on the line where exception is thrown, that would help. – Siva Gopal Dec 30 '16 at 12:51
  • Yes I already did add CardModel script to the card GameObject. The problem here, as you said, is coming from cardModel. Even though its intantiated – kimovic Dec 30 '16 at 13:11
  • I think your issue is that "cardBack" is never assigned a value. Line 20 in CardModel is either `spriteRenderer.sprite = cardback;` or its closing bracket, depending on if your editor is 0 or 1 indexed. – CDove Dec 30 '16 at 14:16

0 Answers0