首页 > 解决方案 > 当所有 9 个面板具有相同的颜色时触发布尔

问题描述

我有一个画布,它有一个空的游戏对象作为子对象,它又具有 9 个改变颜色的面板,当所有 9 个面板具有相同的颜色时,我想触发一个布尔值。

我试图获取 Image 组件,但它显示错误:无法将类型隐式转换UnityEngine.Colorbool.

这是代码:

void Update()
{
    foreach(Transform child in transform)
    {
        if(child.GetComponent<Image>().color = Color.red)
          {
             Debug.Log("yess");
          }
    }
}

标签: c#unity3d

解决方案


首先,对于您要使用的条件,==不要使用=.

其次,目前您正在单独检查每个图像颜色,但不知道所有图像是否同时匹配颜色。

使用LinqAll你可以做到

using System.Linq;

...

// If you can reference these already via the Inspector you can delete the Awake method    
[SerializeField] private Image[] images;

// Otherwise get them ONCE on runtime
// avoid repeatedly using GetComponent especially also iterating through many
void Awake ()
{
    var imgs = new List<Image>();
    foreach(Transform child in transform)
    {
        imgs.Add(child.GetComponent<Image>();
    }
    images = imgs.ToArray();

    // You probably could also simply use 
    //images = GetComponentsInChildren<Image>(true);
}

void Update() 
{ 
    // This returns true if all images have red color
    if(images.All(image => image.color == Color.red))
    {
        Debug.Log("yess"); 
    } 
}

推荐阅读