- Home /
How to Undo SharedMaterial set in CustomEditor?
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);
}
}
Answer by jspease · Feb 29, 2012 at 05:33 AM
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);
}
Thank you, that worked perfectly. I find that it even works nicely in combination with a SceneUndo that I do in the same function for another Operation that I do there before the Texture Assign, so now it Undo's both correctly with just one click. That's a very nice side-effect :)