Unity中如何检测按钮未被选中并修改其他按钮颜色?
Unity按钮选中状态颜色切换问题修复
你的代码逻辑有个核心问题:每个按钮的OnSelect事件只有在自身被选中时才会触发,所以当某个按钮被选中时,只有该按钮的脚本会执行OnSelect方法,此时eventData.selectedObject != newButton的条件永远不成立,自然不会修改其他按钮的颜色。
解决思路
- 当当前按钮被选中时,遍历所有目标按钮,将自身设为选中颜色,其余按钮设为未选中颜色
- 缓存
Image组件,避免重复调用GetComponent浪费性能 - 可选优化:如果只需要处理特定区域的按钮,建议通过父物体获取子按钮,而非
FindObjectsOfType(避免影响场景中无关按钮)
修改后的代码
using UnityEngine.EventSystems; using UnityEngine.UI; public class TheLobbySelectorButtons : MonoBehaviour, ISelectHandler { public GameObject newButton; private Button[] buttonsArray; private Image buttonImage; // 提前定义颜色,方便后续调整 private Color selectedColor = new Color32(165, 173, 248, 190); private Color unselectedColor = new Color32(33, 49, 183, 156); private void Awake() { // 缓存自身的Image组件 buttonImage = newButton.GetComponent<Image>(); // 可选:如果按钮都在同一个父物体下,用下面的方式获取更精准 // buttonsArray = transform.parent.GetComponentsInChildren<Button>(); // 原方式:获取场景中所有Button buttonsArray = FindObjectsOfType<Button>(); } public void OnSelect(BaseEventData eventData) { // 遍历所有按钮,逐个设置颜色 foreach (Button btn in buttonsArray) { Image btnImage = btn.GetComponent<Image>(); if (btn.gameObject == newButton) { btnImage.color = selectedColor; Debug.Log(newButton.name + " was selected"); } else { btnImage.color = unselectedColor; } } } public void Click() { Debug.Log("Bruh"); // 点击时同步选中状态 buttonImage.color = selectedColor; // 同步其他按钮为未选中颜色 foreach (Button btn in buttonsArray) { if (btn.gameObject != newButton) { btn.GetComponent<Image>().color = unselectedColor; } } } }
补充说明
- 这样修改后,无论哪个按钮被选中,都会遍历所有目标按钮,正确区分选中/未选中状态并设置对应颜色
- 如果场景中有其他无关的
Button组件,一定要用父物体获取子按钮的方式,避免误改其他UI元素的颜色
内容的提问来源于stack exchange,提问作者EB25BALL Spark
相关产品推荐
相关产品推荐

