Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Changing text Color through variable not working

Discussion in 'Scripting' started by GUIVASCONCELOS, Mar 29, 2022.

  1. GUIVASCONCELOS

    GUIVASCONCELOS

    Joined:
    Sep 3, 2017
    Posts:
    4
    Hi,

    I'm trying to change the color of a text when a button is selected.
    I've declared a serialized private Color var (to change it in Unity) and tried to change it through script as below:

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using UnityEngine.EventSystems;
    5.  
    6. public class changeColorOnClick : MonoBehaviour, ISelectHandler
    7. {
    8.     public Text text;
    9.     public Button button;
    10.     [SerializeField] private Color textColor;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         button = this.GetComponent<Button>();
    15.         //button.OnSelect(TextOnSelect);
    16.     }
    17.  
    18.    void ISelectHandler.OnSelect(BaseEventData eventData)
    19.     {
    20.         text.color = textColor;
    21.     }
    22. }
    When I look at the inspector, when the button is selected the text color changes, but the text itself disappears.
    However, if I change that line as follows it simply works

    Code (CSharp):
    1. text.color = Color.black;
    Does anybody know what is happening?
    Thanks!
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,876
    What's the value of the color property set to? I suspect you have alpha at 0. Try assigning black as the default. 0 alpha means full transparency.

    Code (csharp):
    1. private Color textColor = Color.black;
     
  3. GUIVASCONCELOS

    GUIVASCONCELOS

    Joined:
    Sep 3, 2017
    Posts:
    4
    Thank you, Karl.
    You are fully right. I was setting the color using the inspector but I didn't set the transparency.
     
    karl_jones likes this.