一、前言

今天介绍一下非常简单的一个东西,就是使用代码改变Text的字体颜色,那么为什么简单还要介绍呢。

因为今天突然有人问我这个问题,秉承着不坑人的原则去百度了一下,结果没有一个可以答到点子上

所以就从新写一篇文章来介绍一下如何实现。

二、改变字体颜色

就一行代码:

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

public class TextColorChange : MonoBehaviour
{
    public Text text;
    void Start()
    {
        text.color = Color.white;
    }
}

获取到Text的color属性,然后直接改变值就可以了 。。


那么有同学问了,如果想输入RGB的值怎么办:
比如你的RGB值为129 69 69 255:

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

public class TextColorChange : MonoBehaviour
{
    public Text text;
    void Start()
    {
        text.color = new Color(129 / 255f, 69 / 255f, 69 / 255f, 255 / 255f);
    }
}

即可。。


还还还有同学问,我想16进制转颜色可以吗:

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

public class TextColorChange : MonoBehaviour
{
    public Text text;
    void Start()
    {
        ColorUtility.TryParseHtmlString("#A68D00", out Color nowColor);
        //使用
        text.color = nowColor;
    }
}

即可。。

三、在文本中加入改变字体颜色的代码

可以在文本中,加入改变字体颜色的代码来改变颜色,比如:

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

public class TextColorChange : MonoBehaviour
{
    public Text text;
    void Start()
    {
        text.text= "<color=#0000ff>改变字体颜色</color>";
    }
}

RGB颜色查询:
【Unity3D日常开发】使用代码改变Text的字体颜色_改变颜色