In Unity, how to make Text form a light and dark change with the selection of the Toggle option bar

In Unity, how to make Text form a light and dark change with the selection of the Toggle option bar

I encountered a problem when learning Unity's UGUI before: how to make the title of the option bar of the Toggle component follow the selection of the option bar, so that it can be synchronized with the option bar for light and dark (switch) exchange.

I searched a lot of similar questions on the Internet to get answers, and the results are all teaching how to use Toggle to make the option bar with selection ability. Later, I slowly found a way:
as long as the IsOn property of the Toggle component can be monitored in real time, then the synchronization will not be much trouble.

void Update()
    {
    
    
        Tg.onValueChanged.AddListener((bool isOn)=>OnToggleClick(Tg, isOn));
    }//用Toggle.onValueChanged.AddListener来实现实时监听。

As for the change of the text, you can consider adjusting the RGB of the text in the function, or just like me.

public void OnToggleClick(bool value)
    {
    
    
        if(value)
        {
    
    
            SelectText.SetActive(true);
            NomalText.SetActive(false);
        }
        else
        {
    
    
            SelectText.SetActive(false);
            NomalText.SetActive(true);
        }
    }

Insert picture description here

Create two Texts, one is the title in the normal (unselected) state, and the other is the title in the selected state. Place them in the same position, and use the SetActice method to switch.

The overall code is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextToggle : MonoBehaviour
{
    
    
    public GameObject Tab;
    public GameObject NomalText;
    public GameObject SelectText;

    private Toggle Tg;
    private bool isOn;
    void Start()
    {
    
    
        Tg =  Tab.gameObject.GetComponent<Toggle>();
    }

    void Update()
    {
    
    
        Tg.onValueChanged.AddListener((bool isOn)=>OnToggleClick(isOn));
    }

    public void OnToggleClick(bool value)
    {
    
    
        if(value)
        {
    
    
            SelectText.SetActive(true);
            NomalText.SetActive(false);
        }
        else
        {
    
    
            SelectText.SetActive(false);
            NomalText.SetActive(true);
        }
    }
}

Guess you like

Origin blog.csdn.net/Nanceker/article/details/115335657