How can I check the color of GameObjects in an Array and print out their color?
Hi, I've been struggling to do this for a while. I found this snippet of code written in JS to check the color of GameObjects with a certain tag. I want to do the same but in C#. Here is that code from 2014.
var counter : int;
var specifiedAmount : int;
function Update()
{
counter = 0;
for(var go : GameObject in GameObject.FindGameObjectsWithTag("Tile"))
{
if(go.renderer.material.color == Color.blue)
{
counter++;
}
}
}
However, I have found that the "go.renderer" line is no longer available in Unity 5. Is there any fix for this?
Here is my code:
using UnityEngine;
using System.Collections;
public class ChangeColor : MonoBehaviour {
float timeLeft = 10.0f;
int counter;
Renderer rend;
// Use this for initialization
void Start () {
counter = 0;
rend = GetComponent<Renderer> ();
}
// Update is called once per frame
void Update () {
timeLeft -= Time.deltaTime;
if (timeLeft < 0) {
Debug.Log ("You covered " + counter + " tiles in 10 seconds!");
}
foreach (GameObject go in ..................) {
counter++;
}
}
void OnCollisionEnter(Collision col) {
rend.material.color = Color.blue;
}
}
What would I add to make it do what I want it to do?
Thanks,
I think you need to use GetComponent to do what you're trying to do.
An updated version of that JS code would look like this:
foreach (GameObject go in GameObject.FindGameObjectsWithTag("Tile"))
{
if(go.GetComponent<Renderer>().material.color == Color.blue)
{
counter++;
}
}
That's right Can you help me with that?
If you want to keep things similar to how you have them, you will probably have to split your one class into two. The ChangeColor class would be attached to each of your game objects that is tagged "Tile" and would consist only of OnCollisionEnter like
void OnCollisionEnter(Collision col)
{
gameObject.GetComponent<Renderer>().material.color = Color.blue;
}
The other class would be responsible for the timer and the counting and would be attached to an empty game object in the scene. It would look something like
public class GameControl : $$anonymous$$onoBehaviour
{
float timeLeft = 10.0f;
int counter;
void Start()
{
counter = 0;
}
void Update()
{
timeLeft -= Time.deltaTime;
if(timeLeft <= 0)
{
foreach(GameObject go in GameObject.FindGameObjectsWithTag("Tile"))
{
if (go.GetComponent<Renderer>().material.color == Color.blue)
{
counter++;
}
}
Debug.Log("You covered " + counter + " tiles in 10 seconds!");
}
}
}
The idea of the game is to run over as many tiles as possible and turn as many of them as you can to blue in 10 seconds and then display how many tiles are blue.