Skip to content

Instantly share code, notes, and snippets.

@hariedo
Last active November 4, 2023 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hariedo/eab1b3fe22c136d3f781a467a6061207 to your computer and use it in GitHub Desktop.
Save hariedo/eab1b3fe22c136d3f781a467a6061207 to your computer and use it in GitHub Desktop.
Unity component to replace materials whenever enabled
// ReplaceMaterial.cs
//
using System.Collections.Generic;
using UnityEngine;
namespace Screenplay
{
//
// When enabled, all materials (or all materials matching given original)
// in this object are replaced with another material. When disabled, the
// replacements made are undone. Can work with all Renderer types in this
// game object, or optionally all Renderers in all active children of this
// object.
//
public class ReplaceMaterial: MonoBehaviour
{
[Tooltip("The material to be replaced; leave None for all materials")]
public Material original;
[Tooltip("The material to be used instead of original materials")]
public Material replacement;
[Tooltip("If true, all children renderers are affected")]
public bool children = true;
public struct Slot
{
public int index;
public Renderer render;
public Material material;
}
private List<Slot> replacements;
void OnEnable()
{
replacements = new List<Slot>();
Renderer[] renders;
if (children)
renders = GetComponentsInChildren<Renderer>();
else
renders = GetComponents<Renderer>();
foreach (Renderer render in renders)
{
bool replaced = false;
Material[] materials = render.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
if (original == null || materials[i] == original)
{
Slot slot = new Slot();
slot.render = render;
slot.index = i;
slot.material = materials[i];
replacements.Add(slot);
materials[i] = replacement;
replaced = true;
}
}
if (replaced)
render.sharedMaterials = materials;
}
}
void OnDisable()
{
if (replacements == null)
return;
foreach (Slot slot in replacements)
{
Material[] materials = slot.render.sharedMaterials;
materials[slot.index] = slot.material;
slot.render.sharedMaterials = materials;
}
replacements = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment