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

Unity中GUI.Label()如何同时设置字体大小与颜色?解决参数过载错误

Unity GUI.Label 同时设置字体大小和颜色的解决方法

我正在制作一个计分系统,想要修改GUI.Label()的字体大小和颜色,但每次尝试同时设置这两个属性时都会报错:

No overload for method 'Label' takes 4 arguments.

目前的代码:

private void OnGUI()
{
    
    GUIStyle s = new GUIStyle();
    s.fontSize = 30;
    GUI.contentColor = Color.red;
    GUI.Label(new Rect(0, 0, 300, 100), "Score: " + points, s, "color");
}

报错的直接原因是你给GUI.Label传了4个参数,但Unity的GUI.Label没有对应参数数量的重载方法,最后那个"color"参数完全多余,这才触发了错误。

要同时设置字体大小和文本颜色,直接把颜色属性配置到GUIStyle对象里就可以了,不需要单独调用GUI.contentColor,修改后的代码如下:

private void OnGUI()
{
    GUIStyle s = new GUIStyle();
    s.fontSize = 30;
    s.normal.textColor = Color.red; // 将颜色设置到样式的普通状态文本颜色
    GUI.Label(new Rect(0, 0, 300, 100), "Score: " + points, s);
}

另外,考虑到OnGUI()会每帧调用,每次都创建新的GUIStyle对象会浪费性能,建议把样式的初始化放到Start()方法里复用:

private GUIStyle scoreStyle;

private void Start()
{
    scoreStyle = new GUIStyle();
    scoreStyle.fontSize = 30;
    scoreStyle.normal.textColor = Color.red;
}

private void OnGUI()
{
    GUI.Label(new Rect(0, 0, 300, 100), "Score: " + points, scoreStyle);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:28:19