简体   繁体   中英

Unity toggle throws NullReferenceException: Object reference not set to an instance of an object

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.

The first example you provided throws the same NullReferenceException when I tested it. It sounds like you've attached a Toggle through the GUI to the instance of Test, but not to the instance of GridManager.

Check in the scene GUI where you have GridManager attached to a GameObject, and make sure that it doesn't say Grid Toggle : None (Toggle) in the script details. If it does, that's your problem right there. Do whatever you did to assign the Toggle object to the Test code to assign it to the GridManager code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM