Search Unity

[Help] Toggle - ison?

Discussion in 'Scripting' started by Aprial, Jan 24, 2015.

  1. Aprial

    Aprial

    Joined:
    Dec 22, 2013
    Posts:
    28
    Hello,

    I am using Unity4.6. I would like to check value of the Toggle is true/false. I get error on "tog.isOn":

    //Using c#:
    usingUnityEngine;
    usingSystem.Collections;
    usingUnityEngine.UI;

    voidStart()
    {
    Toggle tog = GetComponentInChildren<Toggle>();

    if (tog.isOn) {
    Debug.Log ("Hello");
    tog.isOn = false;
    }
    }

    ----
    Display error message
    Error:
    NullReferenceException: Object reference not set to an instance of an object
    VolumeOn.Start () (at Assets/JackScript/VolumeOn.cs:21)

    Please advice.

    Thank you for your help,
    April
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    That would indicate that GetComponentInChildren doesn't actually find the component and therefore is set to NULL. Try to: Debug.Log(tog); to see if it set to something or if it's NULL.
     
  3. Aprial

    Aprial

    Joined:
    Dec 22, 2013
    Posts:
    28
    I got error on “tog.isOn = true;”

    Toggle tog = GetComponentInChildren<Toggle>();
    Debug.Log (tog); // Display Null

    // Display error message: Object reference not set to an instance of an object
    tog.isOn = true;
     
  4. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    That means that Unity can't find a "Toggle" component in the GameObject, nor in any of its childs. Is the component really there? Is it active? GetComonentInChildren only returns active components.
     
  5. Aprial

    Aprial

    Joined:
    Dec 22, 2013
    Posts:
    28
    Thank you for your respong. I am trying to find value of “Is On”. Please refer to attachment image.
    I made following changes and display “False” value.
    // C# code:
    bool toggle = GetComponent<UnityEngine.UI.Toggle>();
    Debug.Log ("toggle: " + toggle); // Display “False”

    toggle.isOn = false; // Display error message
     

    Attached Files:

  6. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Try something like this:

    Code (CSharp):
    1. Toggle tog = GameObject.Find("Sound Toggle").GetComponent<Toggle>();
    2.  
     
  7. Aprial

    Aprial

    Joined:
    Dec 22, 2013
    Posts:
    28
    Display error message:

    // NullReferenceException: Object reference not set to an instance of an object
    publicToggletoggle;
    voidStart()
    {
    Toggle tog = GameObject.Find("Sound Toggle").GetComponent<Toggle>();
     
  8. Aprial

    Aprial

    Joined:
    Dec 22, 2013
    Posts:
    28
    Thank you PHJ, I modify the program and it is working. -Aprial