Search Unity

Toggle and OnValueChanged with inverse dynamic value ?

Discussion in 'UGUI & TextMesh Pro' started by anthonov, Oct 23, 2019.

  1. anthonov

    anthonov

    Joined:
    Sep 24, 2015
    Posts:
    160
    With a toggle we can use a unityEvent to call function with dynamic parameters, like if toggle is ON then otherThing.gameObject.setActive() is also ON.
    Very usefull to save script use, but can it be inversed?
    I would like : if toggle is ON, then other gameObject is OFF.
     
    MilenaRocha likes this.
  2. Marrt

    Marrt

    Joined:
    Feb 7, 2012
    Posts:
    613
    I think this is an elegant solution:
    Attach this component to your Toggle gameobject and check out the Inspector:

    Code (CSharp):
    1. using UnityEngine.EventSystems;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4.  
    5. public class InvertedToggleEvent : MonoBehaviour{
    6.  
    7.     //wont show in inspector
    8.     //public    UnityEngine.Events.UnityEvent<bool> toggleEvent;
    9.  
    10.     //this will show in inspector
    11.     [System.Serializable]
    12.     public class UnityEventBool : UnityEngine.Events.UnityEvent<bool>{}
    13.     public    UnityEventBool onValueChangedInverse;
    14.  
    15.  
    16.     private void Start()
    17.     {
    18.         GetComponent<Toggle>().onValueChanged.AddListener( (on)=>{ onValueChangedInverse.Invoke(!on); } );
    19.     }
    20. }
    21.  
     
    efge and kir1251 like this.
  3. Gamer_Tom

    Gamer_Tom

    Joined:
    Apr 10, 2023
    Posts:
    5
    How to do that without a script?
     
  4. Marrt

    Marrt

    Joined:
    Feb 7, 2012
    Posts:
    613
    I believe nothing has changed since then, so you don't.