- Home /
Toggle material color and shader
I have a button that when clicked, finds a specific child(ren) and changes each material's color to green. Then, when clicked again, I would like for it to revert back to the original color. Considering there are multiple children that get effected, it seems impractical to store each original color in an array. Any ideas on how I can accomplish this? This is what I have so far:
// Public variables
public Transform mainObj;
// Use this to highlight sections of obj
public void HighlightObj (){
// Loop through children to find highlightable sections
foreach(Transform child in mainObj)
{
if(child.name.Contains("selectable"))
{
foreach(Material mat in child.renderer.materials)
{
mat.color = Color.green;
mat.shader = Shader.Find("Unlit/Masked Colored");
}
}
}
}
I've tried using the UnityEditor PrefabUtility function to revert to prefab settings but I haven't had any luck.
Answer by GameVortex · Nov 14, 2013 at 12:56 PM
The PrefabUtility is not available in runtime, and objects do not have any prefab connections in runtime either, so reverting is not an option unfortunately.
Because you want to change the all materials on each renderer, there is not many ways around it other than storing them in an array. But instead of one huge array for all objects, you could maybe use a class for each selectable object that stores its values in its own array. Something like this:
public class SelectableObject
{
private Color[] savedColors;
private Shader[] savedShaders;
public void Select()
{
savedColors = new Color[renderer.materials.Length];
savedShaders = new Shader[renderer.materials.Length];
for(int i = 0; i < renderer.materials.Length, i++)
{
savedColors[i] = renderer.materials[i].color;
savedShaders[i] = renderer.materials[i].shader;
renderer.materials[i].color = Color.green;
renderer.materials[i].shader = Shader.Find("Unlit/Masked Colored");
}
}
public void Deselect()
{
for(int i = 0; i < renderer.materials.Length; i++)
{
renderer.materials[i].color = previousColors[i];
renderer.materials[i].shader = previousShaders[i];
}
}
}