renderer.materials not working.

Hey guys, here is my code.

function Start() {

    selection = Random.Range(0, allBTextures.Length);
    
    skeleton = this.transform.FindChild("skeleton").transform.GetComponent(SkinnedMeshRenderer);
    bodyMat = allBTextures[selection];
    headMat = allHTextures[selection];
	skeleton.materials[0] = bodyMat;
	skeleton.materials[1] = headMat;

}

The problem is that the materials don’t change.

If I change it to ‘skeleton.material = bodyMat’ then it works but of course only changes the first material, leaving the second on the same.

With both set to ‘skeleton.materials’ it doesn’t throw any errors rather it just doesn’t change the material. Why is this? As far as I knew this was meant to worked.

Cheers.

1 Answer

1

Try like this:

Material[] mats = new Materials[]{bodyMat, headMat};
skeleton.materials = mats;

This is the same with all Unity objects when you try to access them with .

It should be a way to assign individual elements and let Unity know the array changed, so that it re-evaluates its content. It's a bit silly both from a conceptual and a performance point of view that you need to re-assign a whole array if you need to change just a single element. Good workaround though.

Apparently it can be done without using new, which should yield better performance and also allows you to change just what you need from the array: Material[] mats = skeleton.materials; mats[1] = headMat; skeleton.materials = mats; You need a temporary var though. It doesn't work if you change directly in skeleton.materials[1] and just assign skeleton.materials to itself.

Ok we have to temporarily save the materials. Because unity 3d doesn't support changing a single variable in the list of materials like skeleton.materials[3] = bodyMat ; ? Why can't it do this simple action?