Changing text Color through variable not working

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:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class changeColorOnClick : MonoBehaviour, ISelectHandler
{
    public Text text;
    public Button button;
    [SerializeField] private Color textColor;
    // Start is called before the first frame update
    void Start()
    {
        button = this.GetComponent<Button>();
        //button.OnSelect(TextOnSelect);
    }

   void ISelectHandler.OnSelect(BaseEventData eventData)
    {
        text.color = textColor;
    }
}

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

text.color = Color.black;

Does anybody know what is happening?
Thanks!

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.

private Color textColor = Color.black;

Thank you, Karl.
You are fully right. I was setting the color using the inspector but I didn’t set the transparency.

1 Like