Unity中通过C#脚本修改Button的normalColor报错求助
你的问题出在两个核心点:
- 未引用
UnityEngine.UI命名空间,导致无法识别Button的colors属性 - 直接给
colors赋值单个Color是错误操作——colors是ColorBlock类型,用于管理按钮全状态(正常、按下、选中等)的颜色集合,不能直接替换为单一Color值
正确修改步骤
- 必须在代码顶部添加UI命名空间引用,否则无法访问Button的颜色相关属性:
using UnityEngine.UI;
- 避免在Update中重复获取组件,提前缓存Button对象以优化性能
- 通过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
相关产品推荐
相关产品推荐

