How do I apply Default-Diffuse material to a MeshRenderer in code?

As part of a custom mesh script, in edit mode, I have a menu item that creates an empty game object to host the custom mesh component as well as adds a MeshFilter and a MeshRenderer.

GameObject go = new GameObject();
go.name = "Expandable Plane";
go.AddComponent("MeshFilter");
go.AddComponent("MeshRenderer");

However, the MeshRenderer has no materials or sharedMaterials set on it. When I manually create primitives like cubes or spheres, the MeshRenderer automatically has the Default-Diffuse material applied. I’d like to apply this to my MeshRenderer, but am struggling to actually find the material using an Editor script.

GameObject.Find("Default-Diffuse");

Turns up null, so does:

Shader.Find("Default-Diffuse");

I know there’s a “Diffuse” shader that I could make a new material instance of, but I want to use the Default-Diffuse material as a sharedMaterial to avoid leaks.

The following undocumented function seems to work in editor scripts:

var mat = AssetDatabase.GetBuiltinExtraResource<Material>("Default-Diffuse.mat");

Here’s a simple snippet:

//set the default material
MeshRenderer mr = go.GetComponent<MeshRenderer>();
mr.material = new Material(Shader.Find("Diffuse"));

My current hack solution is to temporarily create another primitive (plane, cube, whatever) and get the Default-Diffuse material from its sharedMaterial and apply it to my new object.

GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Plane);
primitive.active = false;
Material diffuse = primitive.GetComponent<MeshRenderer>().sharedMaterial;
DestroyImmediate(primitive);
// ...
go.renderer.sharedMaterial = diffuse;

If you are using a render pipeline, you can now use: GraphicsSettings.defaultRenderPipeline.defaultMaterial

Try that :

Material diffuse = new Material
(
    "Shader \"Tutorial/Basic\" {

"
+" Properties {
"
+" _Color ("Main Color", Color) = (1,1,1,1)
"
+" }
"
+" SubShader {
"
+" Pass {
"
+" Material {
"
+" Diffuse [_Color]
"
+" }
"
+" Lighting On
"
+" }
"
+" }
"
+“}”
);

renderer.sharedMaterial = diffuse;

More infos : http://docs.unity3d.com/Documentation/ScriptReference/Material.Material.html

Late answer, but, here’s a way of getting it without creating a default primitive :slight_smile:

// using System.Reflection;
// using UnityEditor;
MethodInfo getBuiltinExtraResourcesMethod;
Material GetDefaultMaterial() {
	if( getBuiltinExtraResourcesMethod == null ) {
		BindingFlags bfs = BindingFlags.NonPublic | BindingFlags.Static;
		getBuiltinExtraResourcesMethod = typeof( EditorGUIUtility ).GetMethod( "GetBuiltinExtraResource", bfs );
	}
	return (Material)getBuiltinExtraResourcesMethod.Invoke( null, new object[] { typeof( Material ), "Default-Diffuse.mat" } );
}