In a CustomEditor I’m creating I am trying to set a few new Materials, but somehow the Undo function doesn’t seem to grip when I use SharedMaterial. When I use just Material instead of sharedMaterial, I end up with leaking materials and new Instances that I do not want.
My code goes something like this:
Undo.RegisterSceneUndo("Assigning Textures");
Renderer[] renderers = user.gameObject.GetComponentsInChildren<Renderer>();
if(renderers != null)
{
foreach(Renderer r in renderers)
{
foreach(Material m in r.sharedMaterials)
{
if(m.HasProperty("_MainTex")) m.SetTexture("_MainTex", t);
}
}
RegisterSceneUndo doesn't work here because the shared material is an asset, which doesn't exist in the scene. So in this case you have to be more specific about which things you want to be able to undo, by using Undo.RegisterUndo, like this:
Renderer[] renderers = user.gameObject.GetComponentsInChildren<Renderer>();
if(renderers != null)
{
List<Material> materialsToEdit = new List<Material>();
foreach(Renderer r in renderers)
{
foreach(Material m in r.sharedMaterials)
{
if(m.HasProperty("_MainTex"))
materialsToEdit.Add(m);
}
}
Undo.RegisterUndo(materialsToEdit.ToArray(), "Assigning Textures");
foreach(Material m in materialsToEdit)
m.SetTexture("_MainTex", t);
}