Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - trigger bool when all 9 panel have the same color

I have a canvas which has empty gameobject as child which in turn has 9panels which changes color, I want to trigger a bool when all the 9panels have the same color.

I have tried to get the Image component but it shows error: Cannot implicitly convert type UnityEngine.Color to bool.

Here's the code:

void Update()
{
    foreach(Transform child in transform)
    {
        if(child.GetComponent<Image>().color = Color.red)
          {
             Debug.Log("yess");
          }
    }
}
question from:https://stackoverflow.com/questions/65672014/trigger-bool-when-all-9-panel-have-the-same-color

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all for conditions you want to use == not assign it using =.

Second currently you are checking each image color individually but will not know if all the images match the color at the same time.

Using Linq All you can do

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"); 
    } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...