- Home /
Checking the color of game objects with specific tag.
Hello ! I need a code for loading the next scene in an if the condition satisfied loading nex scene is not a problem but I can not set my condition. The condition is if color all game objects wit tag "Cube" do something.
if(all game objects with tag "Cube".color == "yellow") {
DO SOMETHING
}
Answer by Sxythe · Feb 21, 2020 at 02:58 PM
You can put the cubes in an array and use a for loop to check if the color is yellow like this
private GameObject[] m_Cubes;
private void Start()
{
m_Cubes = GameObject.FindGameObjectsWithTag("Cube");
}
void Update()
{
int amount = 0;
for (int i = 0; i < m_Cubes.Length; i++)
{
if (m_Cubes[i].GetComponent<Renderer>().material.color == Color.yellow)
{
amount++;
}
}
if (amount >= m_Cubes.Length)
{
//DO SOMETHING
}
}
No need for counting, and it's more performant to stop checking as soon as you find a non-yellow one.
void Update()
{
CheckColours();
}
void CheckColours()
{
for (int i = 0; i < m_Cubes.Length; i++)
{
if (m_Cubes[i].GetComponent<Renderer>().material.color != Color.yellow)
{
return;
}
}
//All are yellow, so DO SO$$anonymous$$ETHING
}
Answer by ShadyProductions · Feb 21, 2020 at 02:36 PM
bool areAllObjectsYellow = GameObject.FindGameObjectsWithTag("Cube")
.Select(a => a.GetComponent<YOURCOLORSCRIPT>())
.All(a => a.color == "yellow");
if (areAllObjectsYellow)
{
// Do something
}
For this script you will need using System.Linq;
Also you didn't give a lot of information about where your .color comes from so I assume you have another script on the cube with that property. You just have to replace "YOURCOLORSCRIPT" with the script name.
This is my only script for that game object (cube) I need a condition that if all colors are yellow do something
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Scene$$anonymous$$anagement;
using System.Linq;
public class ChangeColor : $$anonymous$$onoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.z < -30) {
GetComponent<Renderer>().material.color = Color.yellow;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612223739im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Rainbow Material Script Not properly running 1 Answer