unity检查Toggle是否为on

时间:2019-08-03 20:07:50

标签: c# unity3d

我正在检查是否已打开切换开关。通常我在检查器中使用public Toggle myToggle,但这是我将脚本附加到Toggle上,并且可能错误地使用了GetComponent<Toggle>()

我在NullReferenceException: Object reference not set to an instance of an object行得到if(m_Toggle.isOn)

这是附加到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);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

public ToggleSound ()更改为public void ButtonClick()。 在检查器中的On Value Changed框中添加此功能。

enter image description here

答案 1 :(得分:0)

在Unity中选择您的对象,并将其visible属性设置为true。

答案 2 :(得分:0)

显而易见的答案是GetComponent()找不到Toggle实例。

必须在MonoBehavior的实例上调用GetComponent。由于您没有指定实例来调用它,因此您当前在正在使用的ToggleSound实例上调用GetComponent。实际上,您叫this.GetComponent

并且ToggleSound中唯一的Toggle是m_Toggle,目前尚未初始化。因此,将返回值设置为更明智的null。这相当于程序员想知道您的眼镜在鼻子上时在哪里。