Skip to content

Instantly share code, notes, and snippets.

@Theo-Farnole
Created July 10, 2023 13:09
Show Gist options
  • Save Theo-Farnole/966d578a2e7d6d5119f05fc626ad950c to your computer and use it in GitHub Desktop.
Save Theo-Farnole/966d578a2e7d6d5119f05fc626ad950c to your computer and use it in GitHub Desktop.
By inheriting from SerializedEditorWindow instead of EditorWindow, you can make Unity editor windows in exactly the same way you make inspectors: by using only attributes.
/**
*
* Inherit from SerializedEditorWindow, then mark field as [SerializeField] will make them appear in the window
*
* If you want to add some button, you can override OnGUI()
*
* Inspired by the OdinEditorWindow
* "By inheriting from SerializedEditorWindow instead of EditorWindow, you can make Unity editor windows in exactly the same way you make inspectors: by using only attributes."
**/
using System;
using UnityEditor;
using UnityEngine;
public class SerializedEditorWindow : EditorWindow
{
private readonly static string[] IGNORED_FIELDS_NAMES = new string[]
{
"m_SerializedDataModeController",
"m_Script",
nameof(_scrollPosition)
};
[SerializeField] private Vector2 _scrollPosition;
private SerializedObject _serializedObject;
protected virtual void OnEnable()
{
_serializedObject = new SerializedObject(this);
}
protected virtual void OnGUI()
{
if (_serializedObject == null)
{
_serializedObject = new SerializedObject(this);
}
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition);
{
_serializedObject.Update();
SerializedProperty property = _serializedObject.GetIterator();
if (property.NextVisible(true))
{
do
{
if (IsFieldIgnored(property.name)) continue;
EditorGUILayout.PropertyField(_serializedObject.FindProperty(property.name));
}
while (property.NextVisible(false));
}
_serializedObject.ApplyModifiedProperties();
}
GUILayout.EndScrollView();
}
private static bool IsFieldIgnored(string fieldName)
{
int index = Array.FindIndex(IGNORED_FIELDS_NAMES, x => x == fieldName);
return index != -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment