- Home /
Change the materials of a list of game objects to one material, and then change it back to their old ones.
I want to change all of materials on a game object's child objects to a simple silhouette material, and then change them back to the old ones when user inputs a certain command. My functions are as below:
public List<Material> mats;
public Material SilhouetteMaterial;
public void AttachSilhouette()
{
mats = new List<Material>();
var childrenRenderers = objects.GetComponentsInChildren<Renderer>();
foreach (var childRenderer in childrenRenderers)
{
//Material NewOne = new Material(childRenderer.material);
//mats.Add(NewOne);
mats.Add(childRenderer.material);
childRenderer.material = SilhouetteMaterial;
}
}
public void DetachSilhouette()
{
var childrenRenderers = objects.GetComponentsInChildren<Renderer>();
int t = 0;
foreach (var childRenderer in childrenRenderers)
{
childRenderer.material = mats[t];
t++;
}
mats.Clear();
}
However this problem is, executing function AttachSilouette() seems to give me a list of silhouette material instead of the original materials on these game objects that I want to cache. If I comment out the line childRenderer.material = SilhouetteMaterial; then it will actually give me a list of the materials that I want to cache. Can someone tell me why this is happening? I figured that maybe the list only stores a list of reference so I tried creating a material instance before adding it to the list however it doesn't work either.
Answer by CheetahSpeedLion · Jul 13, 2017 at 01:53 AM
I'm not sure but you might be saving a reference to the renderer's material slot instead of the actual material in that slot. Try making a new material in your list by using the Material constructor and copying the "original Material" instead of referencing it https://docs.unity3d.com/ScriptReference/Material-ctor.html
Alternatively, play around with switching shaders instead of materials. I do this in my game for a similar effect. See "flashing effect" in Google for examples.
Areleli
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
How to compare 2 materials? 2 Answers
Issue with Mesh Renderer and Skinned Mesh Renderer 0 Answers
Having a problem with the second material (on the same renderer) 0 Answers
How do I change the material of a prefab when it is not in the hierarchy? 0 Answers