在使用Unity时,我制作了一个简单的代码,我认为它没有任何问题:
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>();
}
}
为了测试对象和脚本,我制作了一个测试代码脚本和一个gameObject(所有这些都是在关注youtube上的教程)这里是测试代码:
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);
}
}
}
}
并且在团结运行时没有问题......但是,每次按下按钮(带有:单击我的按钮),控制台都会显示:
NullReferenceException:未将对象引用设置为对象的实例 DebugCard.OnGUI()(在Assets / scripts / DebugCard.cs:20)
我在stackOverFlow中看到了很多NullReferenceException问题,但仍然无法修复它!