In Unity, I have some simple code that works:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Test : MonoBehaviour {
public Toggle GridToggle;
// Use this for initialization
void Start () {
GridToggle.isOn = true;
print (GridToggle.isOn);
}
}
As I said, this works just fine, logging 'true' to the console. However, I have a second batch of code here, that is almost the exact same, but for some bizarre reason it does not seem to work:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class GridManager : MonoBehaviour {
public Sprite[] gridColors = new Sprite[0];
public int defaultSprite = 0;
public Toggle GridToggle;
public SpriteRenderer spriteRenderer;
// Use this for initialization
void Start () {
//Same exact thing!
GridToggle.isOn = true;
print (GridToggle.isOn);
//Same exact thing!
spriteRenderer = GetComponent<SpriteRenderer> ();
spriteRenderer.sprite = gridColors [defaultSprite];
}
void Update () {
spriteRenderer = GetComponent<SpriteRenderer> ();
spriteRenderer.enabled = true;
}
}
What this does is strange: It logs 'true' to the console, but at the same time, on the line that says GridToggle.isOn = true;
, it throws: NullReferenceException: Object reference not set to an instance of an object. I want the second code to work, but I cannot figure out what I am doing wrong, and how it is any different from the first bit.