Get material of Children's children and Change tag help

Hi all , Im having some trouble with my code.

Basically , i am trying to get my objects to change their own Tags bassed on their material attached. Their materials are solid colours (Red , blue , etc)

So far , i’m trying to use this code. Basically i have 1 object named pack that has a few sets. Each set has a few cubes as shown in the image . The code isn’t working obviously because idk how to do this and this is me just trying to use whatever knowledge i have , hence why i need help :slight_smile:


this is my code atm :

Material Red;
Material Yellow;
Material Blue;
// Have materials dragged into this on unity 

Void Start() {

    int ChildrenCount = transform.childCount;    
    // Get all children (I think this is only counting my Sets)

    List<Material> MaterialChecker = new List<Material>();                  
    // Make new List for materials

    for (int i = 0; i < ChildrenCount; i++)                                                    
   // loop through children
        GameObject children = transform.GetChild(i).gameObject;                         
        children.GetComponent<Renderer>().materials = MaterialChecker.ToArray();

                if (children == Red)
                    tag = "Red";
                if (children == Yellow)
                    tag = "Yellow";
                if (children == Blue)
                    tag = "Blue";


This Start script is attached to “Pack” because this script will have to check all the Cubes in all the sets.

All Cubes have a Default tag of “Cube” incase that helps.

The error i get is "set1 doesn’t have a renderer attached.

So essentially i need a way to get this script to check the Child’s Children’s material and based on their material , change their tag accordingly

Could someone please help evaluate my code and help me out ? Thank you all !
I’m still somewhat new to programming so bare with my ignorance , i’m still learning :slight_smile:

Try this:

public Material Red;
public Material Yellow;
public Material Blue;

// Have materials dragged into this on unity 
void Start()
	Transform pack = transform ;
	int packChilCount = pack.childCount ;
	for( int i = 0 ; i < packChilCount ; ++i )
		Transform set = pack.GetChild( i ) ;
		int setChildCount = set.childCount ;
		for( int j = 0 ; j < setChildCount ; ++j )
			SetTagAccordingToMaterial( set.GetChild( j ) ) ;

private void SetTagAccordingToMaterial( Transform cube )
	Renderer cubeRenderer = cube.GetComponent<Renderer>();
    if( cubeRenderer.material == Red ) tag = "Red" ;
    else if( cubeRenderer.material == Yellow ) tag = "Yellow" ;
    elseif( cubeRenderer.material == Blue ) tag = "Blue" ;