- Home /
Dynamically Replace SkinnedMesh Materials
I have a character that has a SkinnedMesh Renderer attached to it with multiple materials applied. I want to change these dynamically via code, but I can't seem to get it right:
This only changes the first material applied:
unitColours.objectsBody.renderer.material = unitColours.redTexture.body;
This doesn't do anything:
unitColours.objectsBody.renderer.materials[0] = unitColours.redTexture.body;
unitColours.objectsBody.renderer.materials[1] = unitColours.redTexture.pack;
This doesn't do anything, either:
unitColours.objectsBody.renderer.sharedMaterials[0] = unitColours.redTexture.body;
unitColours.objectsBody.renderer.sharedMaterials[1] = unitColours.redTexture.pack;
Nor this:
unitColours.objectsBody.GetComponent(SkinnedMeshRenderer).materials[0] = unitColours.redTexture.body;
unitColours.objectsBody.GetComponent(SkinnedMeshRenderer).materials[1] = unitColours.redTexture.pack;
A Screenshot of the inspector:
Any ideas how I can dynamically change the material elements? Thanks
Have you checked all the calling code and the references?
Or maybe you have other code undoing the changes?
have you tried making a mew $$anonymous$$aterial[], populating it and then pushing it back on? renderer.materials=new $$anonymous$$aterial[]{mymaterial1,mymaterial2};
Answer by Westbang · Jun 14, 2020 at 03:58 PM
Use this Function:
void set_skinned_mat(string obj_name, int Mat_Nr, Material Mat)
{
GameObject obj = GameObject.Find(obj_name);
SkinnedMeshRenderer renderer = obj.GetComponentInChildren<SkinnedMeshRenderer>();
Material[] mats = renderer.materials;
mats[Mat_Nr] = Mat;
renderer.materials = mats;
}
and use the Function like:
set_skinned_mat("Pilot1", 1, Material1);
Answer by miragetech · Feb 10, 2016 at 05:39 PM
I had the same problem and this solution worked for me: http://answers.unity3d.com/questions/175370/renderermaterials-not-working.html You need to assign the "materials" array as a whole. Otherwise, it won't work.
Regards, Salvador
Your answer
![](https://koobas.hobune.stream/wayback/20220613143033im_/https://answers.unity.com/themes/thub/images/avi.jpg)