在运行时更改文本颜色(Unity)?

Change color of text during runtime (Unity)?

我有一个 GameObject 嵌入在我的 Canvas 中,它有一个“文本(脚本)”组件。我希望在该元素的运行时更改 color.a 属性。有没有人知道如何去做?我似乎无法使用任何 GetComponent<Type> () 命令访问它。

据我所知,您必须为 text.color 分配新颜色。您可以制作自己的颜色来分配或使用其中一种标准颜色:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class test : MonoBehaviour {

public Text text;

void Start () 

    {
       text = gameObject.GetComponent<Text> ();
       text.color = Color.white;
    }
}

使用CrossFadeAlpha。请参阅 link 了解用法。

如果您想更改文本颜色的 R、G、B 或 A 分量,您可以这样做:

Public Text text;
float r=0.2f,g=0.3f,b=0.7f,a=0.6f;

void Start()
{
  text=gameobject.GetComponent<Text>();
  text.color= new Color(r,g,b,a);
}

public Text myText;

Attach this to the UI component of text in Hierarchy

myText.color = Color.green;
myText.text = "Enter anything, will display in UI Text";

您可以使用颜色属性为文本提供颜色。

可以通过两种方式完成 -> 使用颜色静态属性和颜色 class 构造函数。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ColorDemo : MonoBehaviour {

    [SerializeField]
    Text infoText;

    void Start () {
       infoText.text = "Hello World";
       infoText.color = Color.red; //Red color using Color class
       //Red color using hex value. (255,0,0) => 255/255, 0/255, 0/255) => (1,0,0)
       infoText.color = new Color(1f, 0f, 0f); 
       // Color with opacity value. 1 means opaque and 0 means transparent.
       infoText.color = new Color(1f, 0f, 0f, 0.5f); 
    }
}