如何更改UI文本颜色

时间:2016-06-11 16:05:14

标签: c# unity3d scripting

我的脚本适用于3D GameObject,但不适用于Text组件。如何使其在文本上工作?我很感谢你的帮助。

using UnityEngine;
using System.Collections;

public class Colors : MonoBehaviour

{
public float timer = 0.0f;
Renderer rd;

void Start()
{
    rd = gameObject.GetComponent<Renderer>();
}


void Update()
{
    timer += Time.deltaTime;
    if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
    {
        // pick a random color
        Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
        // apply it on current object's material
        rd.material.color = newColor;

        timer = 0;
    }
}

}

1 个答案:

答案 0 :(得分:0)

对于UI文字,您使用Text.color而不是Renderer.material.colorRenderer用于附加Mesh Renderer的3D对象。确保将此附加到附有Text组件的GameObject,否则您将收到错误。

public float timer = 0.0f;
Text txt;

void Start()
{
    txt = gameObject.GetComponent<Text>();
}


void Update()
{
    timer += Time.deltaTime;
    if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
    {
        // pick a random color
        Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
        // apply it on current object's material
        txt.color = newColor;

        timer = 0;
    }
}

Here是适合您的Unity教程。在提出进一步的问题之前,请至少做一个项目。