- Home /
Question by
kjems 1 · Nov 08, 2010 at 02:49 PM ·
instantiatematerialeditor-scripting
Making new material instance of sharedMaterial in editor mode
I would like the ability to make a new instance of a material in a scene or in a prefab and let it be saved with the scene or prefab. This will enable easy customization of materials without the need for manually duplicating a material in the Project view and using that instead.
The code below works for materials in a scene, but if the material is part of a prefab and that prefab is used in another scene the Material reference will be null. I am assuming the material was stored in the original scene and not in the prefab, which makes the error.
Anyone got any ideas on how to solve this?
[CustomEditor(typeof(MeshRenderer))]
public class MeshRendererInspector : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Renderer renderer = target as Renderer;
if (GUILayout.Button("Test Instancing"))
{
renderer.sharedMaterial = new Material(renderer.sharedMaterial);
}
}
}
Comment
Answer by bojlahg · Mar 27, 2012 at 06:46 PM
renderer.materials = new Material[1]; renderer.materials[0] = new Material(renderer.sharedMaterial);