c# - 当所有 9 个面板具有相同的颜色时触发布尔
问题描述
我有一个画布,它有一个空的游戏对象作为子对象,它又具有 9 个改变颜色的面板,当所有 9 个面板具有相同的颜色时,我想触发一个布尔值。
我试图获取 Image 组件,但它显示错误:无法将类型隐式转换UnityEngine.Color
为bool
.
这是代码:
void Update()
{
foreach(Transform child in transform)
{
if(child.GetComponent<Image>().color = Color.red)
{
Debug.Log("yess");
}
}
}
解决方案
首先,对于您要使用的条件,==
不要使用=
.
其次,目前您正在单独检查每个图像颜色,但不知道所有图像是否同时匹配颜色。
使用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");
}
}
推荐阅读
- shell - 如何在所有 . 和/在 10.0.1.0/24 中?
- firebase - RNFirebase v6 推送通知不会同时出现在 iOS 和 Android 中
- python - ListView 中的 Django 表单,表单的 POST 错误
- ios - 调整 UIBarButtonItems 的大小
- slurm - 如何根据作业 ID 查找用于 slurm 作业的命令?
- node.js - 有没有办法将 OracleDB 与 Node 10.15 一起使用?
- unreal-engine4 - 无法投射到演员 - UE4 BP
- ios - 带有 Cordova 的 iOS 13 错误 (WebKit) - 应用程序挂起
- javascript - 为什么这个函数总是返回 null
- python-3.x - 如何让 Salesforce REST API 进行分页?