change material in children

I have a GameObject which has no renderer it’s self, rather everything is a child, they all share the same material. Instead of listing vars for each child in the GameObject, I would rather loop a for that runs through the children and applies the correct material when that prefab is instantiated. Thing is, documentation on this exact process is thin on the ground. How does a for loop work in this case??

var frog : GameObject;
	var randomMatNum : int = Random.Range(1, 5);
	var randomMat : Material;
	var greenFrog : Material;
	var blueFrog : Material;
	var pinkFrog : Material;
	var yellowFrog : Material;
	
	if (randomMatNum == 1) randomMat = greenFrog;
	else if (randomMatNum == 2) randomMat = blueFrog;
	else if (randomMatNum == 3) randomMat = pinkFrog;
	else if (randomMatNum == 4) randomMat = yellowFrog;
	
	
	
	for (var frogChild in frog.GetComponentInChildren(Renderer))
	{
		frogChild.material = randomMat;
	}

Get an error, not sure how this is done TBH.

Hey there! Don’t worry you’re almost there.

In terms of the for loop, you’re close: you shouldn’t need to use a GetComponentInChildren to access their renderers, using .render.material shoul work just fine. As for accessing the children themselves, you would use for (var frogChild : Transform in transform) {, accessing any children (Transforms) within the object the script is attached to.

Also, I suggest instead of using separate variables for each material, use a Material[] array. That way you could assign all your different materials to a single var in the inspector, and then use your Random.Range to return the element of that number.

All in all, your script should end up looking like this:

var randomMatNum : int = Random.Range(1, 5);
var randomMat : Material[];

function Update () {

	for (var frogChild: Transform in transform) {
		frogChild.renderer.material = randomMat[randomMatNum];
	}
}

Have fun with your game! Klep

What error do you get? Your loop has GetComponentInChildren instead of GetComponentsInChildren (plural).

var randomFrogMat : Material;

function Start() {
	var randomMatNum : int = Random.Range(0, 4);
	for (var frogChild: Transform in transform) {
	       frogChild.renderer.material = randomFrogMat[randomMatNum];
	}
}