- Home /
Setting materials at runtime
Hey, I'm trying to change the material of a group of objects at runtime, and I'm coming across a rather strange issue. I have a method which gets me a list of the Transforms of all the objects I need to change (by recursively calling itself over the Transform iterator), and then I'm looping through that and setting the materials array (the entire array). I'm seeing literally no change to the game, but when I ran some diagnostic prints, I found that the renderer seems to have set the materials, but it looks like it's immediately setting them back again. Can anyone tell me what I'm doing wrong here? This is the code I'm using:
Transform[] ts = parent.GetRenderTransforms().ToArray();
for (int i = 0; i < ts.Length; i++ )
{
materials.Add(ts[i], ts[i].renderer.sharedMaterials)
Material[] ms = new Material[ts[i].renderer.materials.Length];
for (int j = 0; j < ms.Length; j++)
{
ms[j] = hourai;
}
ts[i].renderer.materials = ms;
}
Where "hourai" is a variable holding the material I'm trying to set, and "materials" is a Dictionary allowing me to map the original materials back. I'm getting no errors whatsoever, and the debugging I've done all seems to point to it working correctly. Can anyone help here?
EDIT:
I've found that if I don't add the values to the dictionary, then it all works. Can anyone think of a reason that this might cause a problem?
Can you show us the code where the materials dictionary is created? $$anonymous$$y guess is that you're setting and using values from the dictionary but not actually changing them in the dictionary.
Are you sure you want this line:
ts[i].renderer.materials = ms;
I guess this would make more sense:
ts[i].renderer.shared$$anonymous$$aterials = ms;
Assigning to the materials array will create duplicates of your materials for each renderer.
@Bunny83 - For the record, I was using materials and not shared$$anonymous$$aterials on purpose. The material I was assigning was set to dynamically change colour, and I have other instances of the object in the scene, and I wanted each to act independently, so materials was more appropriate.
Answer by Hoeloe · Jul 15, 2013 at 05:10 PM
So it turns out the condition for resetting the materials wasn't set correctly, so it was immediately running through the Dictionary and resetting all the textures. It's fixed now.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110145im_/https://answers.unity.com/themes/thub/images/avi.jpg)