Help with my code

This script is attached on an empty game object called platform.
The platform contains 31 cubes.
What I wanna say is that when colorchange is true, change cube 1 to green.
Anyone can help me with it.

using UnityEngine;
using System.Collections;

public class PlatformScript : MonoBehaviour {

    public static bool colorChange = false;


    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
        if (colorChange == true) {
           
             //transform.GetComponentInChildren("Cube");
            GetComponentInChildren<Renderer> ().material.color = Color.green;
            //gameObject.GetComponent<Renderer> ().material.color = Color.green;
            print ("color is true");
        }
    }

    void LateUpdate(){
            colorChange = false;
        }
} // End class

You post a lot of beginner questions, so I’ll help guide you rather than write the script outright for you so you learn rather than copy.

Use transform.GetChild() using Random.Range with 0 and transform.childCount as parameters to get a random child object. Then use GetComponent() on that object rather than GetComponentInChildren() and set the colour as you’re doing now.

I know I try to learn myself and sometimes I need coaching.

Anything running in Update() should be optimized because as you may be aware of, Update() is called every single frame. In this case, a good idea is to cache these cubes in a array or List:

protected Renderer[] Cubes;

Awake()
{
  Cubes = transform.GetComponentsInChildren<Renderer>();
}

Update()
{
  // First cube
  Cubes[0]...  
}
1 Like