You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中Split分割文本后ColorUtility.TryParseHtmlString解析颜色失败

Unity读取文本文件中十六进制颜色码解析失败问题解决

问题场景

我有一个包含大量十六进制颜色码的文本文件,直接用纯字符串调用ColorUtility.TryParseHtmlString可以正常转换为Color类型,例如:

ColorUtility.TryParseHtmlString("#040720", out newCol)

但通过脚本读取文件中的颜色码时,TryParse始终返回false。我的C#代码如下:

using UnityEngine;

public class SplitString : MonoBehaviour
{
    public TextAsset TextFile; // txt文件共680行,内容示例:   #000000
                                                               //#040720
                                                               //#0C090A
    void Start()
    {
        string[] linesInFile = TextFile.text.Split('\n');

        Color newCol;
        int randNum = Random.Range(0, linesInFile.Length);
        if (ColorUtility.TryParseHtmlString(linesInFile[randNum], out newCol))
            transform.GetComponent<SpriteRenderer>().color = newCol;
        else
            print("Parse failed");
    }
}

将脚本挂载到Sprite Square并指定文本文件后,解析始终失败。

问题原因与解决方法

最初以为是字符串开头的空格导致问题,后来发现真正的原因是每个读取到的字符串末尾带有额外的换行符。通过正则表达式去除这些无效字符后,功能完全正常:

using System.Text.RegularExpressions;

// 去除字符串中的换行符(包括\r和\n)
string pureHex = Regex.Replace(linesInFile[randNum], @"[\r\n]{1,}", "");
// 使用处理后的pureHex调用解析方法
if (ColorUtility.TryParseHtmlString(pureHex, out newCol))
{
    transform.GetComponent<SpriteRenderer>().color = newCol;
}

内容的提问来源于stack exchange,提问作者Andrew07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:12:35