Keith Power
Keith Power

Reputation: 14141

Unity Check if Toggle isOn

I am checking to see if a toggle is on. Normally I use public Toggle myToggle in the inspector but this this I am attaching the script to the Toggle and probably wrongly using GetComponent<Toggle>()

I get NullReferenceException: Object reference not set to an instance of an object on the if(m_Toggle.isOn) line.

This is the script attached to the Toggle

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ToggleSound : MonoBehaviour {

    Toggle m_Toggle;

    // Use this for initialization
    void Start () {
        m_Toggle = GetComponent<Toggle>();
        Debug.Log(m_Toggle);

    }

    public ToggleSound ()
    {
        if(m_Toggle.isOn)
        {
            AudioManager.Instance.SetVolume(0, -80);
        }
        else
        {
            AudioManager.Instance.SetVolume(0, 0);
        }
    }
}

Upvotes: 3

Views: 16466

Answers (3)

miner
miner

Reputation: 1

In Unity select your object and set its visible property to true.

Upvotes: 0

J.K. Harthoorn
J.K. Harthoorn

Reputation: 218

Change public ToggleSound () into something like public void ButtonClick(). In the inspector add this function in the On Value Changed box.

enter image description here

Upvotes: 1

Christopher
Christopher

Reputation: 9804

The obvious answer would be that GetComponent() does not find a Toggle instance.

GetComponent has to be called on a instance of MonoBehavior. As you did not specify a instance to call it on, you currently call GetComponent onto the very instance of ToggleSound you are working with. Effectively you call this.GetComponent.

And the only Toggle in ToggleSound is m_Toggle, currently not Initialized. So the return value is set to the more sensible null. This is the programmer equivalent of wondering where your glasses are, while having it on your nose.

Upvotes: 0

Related Questions