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

Unity中通过C#脚本修改Button的normalColor报错求助

解决Unity 2021中Button的normalColor修改问题

你的问题出在两个核心点:

  • 未引用UnityEngine.UI命名空间,导致无法识别Button的colors属性
  • 直接给colors赋值单个Color是错误操作——colors是ColorBlock类型,用于管理按钮全状态(正常、按下、选中等)的颜色集合,不能直接替换为单一Color值

正确修改步骤

  1. 必须在代码顶部添加UI命名空间引用,否则无法访问Button的颜色相关属性:
using UnityEngine.UI;
  1. 避免在Update中重复获取组件,提前缓存Button对象以优化性能
  2. 通过ColorBlock对象修改指定状态的颜色,而非直接替换整个颜色配置

修正后的完整代码

using UnityEngine;
using UnityEngine.UI; // 关键命名空间

public class ButtonSelector : MonoBehaviour
{
    public string selectedList;
    Button[] buttons; // 直接缓存Button组件,省去Transform转译步骤

    void Start()
    {
        // 获取所有子物体中的Button组件,自动过滤无Button的对象
        buttons = GetComponentsInChildren<Button>();
    }

    void Update()
    {
        int selectedIndex = PlayerPrefs.GetInt(selectedList);
        // 先判断索引有效性,避免数组越界报错
        if (selectedIndex >= 0 && selectedIndex < buttons.Length)
        {
            Button targetBtn = buttons[selectedIndex];
            // 获取当前按钮的颜色配置块
            ColorBlock colorBlock = targetBtn.colors;
            // 修改正常状态的颜色
            colorBlock.normalColor = new Color32(191, 255, 203, 255);
            // 将修改后的配置块赋值回按钮
            targetBtn.colors = colorBlock;
        }
    }
}

额外提示

  • 仅修改normalColor时,保留原有ColorBlock的其他配置(如按下、高亮颜色),不会破坏按钮的原有交互视觉逻辑
  • 如果选中状态并非每帧变化,建议将颜色修改逻辑绑定到选中状态变更的事件中,而非在Update里频繁执行,减少性能消耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:15:27