Skip to content

Instantly share code, notes, and snippets.

@Volantk
Created July 29, 2019 14:35
Show Gist options
  • Select an option

  • Save Volantk/7a6db5dcf89e08fb971c3758d7eeab28 to your computer and use it in GitHub Desktop.

Select an option

Save Volantk/7a6db5dcf89e08fb971c3758d7eeab28 to your computer and use it in GitHub Desktop.
[CustomEditor(typeof(SomeScript))]
public class SomeScriptInspector : Editor
{
private SomeScript Target;
private MaterialEditor _materialEditor;
private void OnEnable()
{
Target = target as SomeScript;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var materialProp = serializedObject.FindProperty("_material");
var materialReference = materialProp.objectReferenceValue as Material;
EditorGUI.BeginChangeCheck ();
// Draw the material field of MyScript
EditorGUILayout.PropertyField (materialProp);
if (EditorGUI.EndChangeCheck ())
{
serializedObject.ApplyModifiedProperties ();
if (_materialEditor != null) {
// Free the memory used by the previous MaterialEditor
DestroyImmediate (_materialEditor);
}
if (materialReference != null) {
// Create a new instance of the default MaterialEditor
_materialEditor = CreateEditor(materialReference) as MaterialEditor;
}
}
if (_materialEditor == null)
{
_materialEditor = CreateEditor(materialReference) as MaterialEditor;
}
else
{
// Draw the material's foldout and the material shader field
// Required to call _materialEditor.OnInspectorGUI ();
_materialEditor.DrawHeader ();
// We need to prevent the user to edit Unity default materials
bool isDefaultMaterial = !AssetDatabase.GetAssetPath (materialReference).StartsWith ("Assets");
using (new EditorGUI.DisabledGroupScope(isDefaultMaterial)) {
// Draw the material properties
// Works only if the foldout of _materialEditor.DrawHeader () is open
_materialEditor.OnInspectorGUI ();
}
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment