Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Last active March 25, 2019 16:43
Show Gist options
  • Save James-Frowen/48c2ef79d4868247fce8b235a659284c to your computer and use it in GitHub Desktop.
Save James-Frowen/48c2ef79d4868247fce8b235a659284c to your computer and use it in GitHub Desktop.
Base Class for editor windows in Unity3d
using UnityEditor;
using UnityEngine;
namespace EditorScripts
{
public abstract class SerializedEditorWindow : EditorWindow
{
/// <summary>
/// Serialization target, can be overridden to allow target to be something other than this editor window
/// </summary>
protected virtual Object Target => this;
protected SerializedObject so;
/// <summary>
/// Unity OnGUI function
/// </summary>
protected void OnGUI()
{
this.beforeGUI();
this.drawGUI();
this.afterGUI();
}
/// <summary>
/// Child classes should override this for their draw gui event
/// </summary>
protected virtual void drawGUI()
{
// nothing
}
/// <summary>
/// draws a property field using a property name
/// </summary>
protected void propertyField(string fieldName, bool includeChildren = true)
{
EditorGUILayout.PropertyField(this.so.FindProperty(fieldName), includeChildren);
}
/// <summary>
/// draws a button
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
protected bool button(string label)
{
return GUILayout.Button(label);
}
/// <summary>
/// Sets up Serialized Object and updates.
/// </summary>
protected virtual void beforeGUI()
{
if (this.so == null)
{
this.so = new SerializedObject(this.Target);
}
this.so.Update();
}
/// <summary>
/// Applies changes to Serialized Object
/// </summary>
private void afterGUI()
{
this.so.ApplyModifiedProperties();
}
/// <summary>
/// Can be called by child class to show the window
/// </summary>
/// <typeparam name="T"></typeparam>
protected static void showWindow<T>() where T : EditorWindow
{
var window = GetWindow<T>();
window.minSize = new Vector2(50, 50);
window.titleContent = new GUIContent(typeof(T).Name);
window.Show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment