Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
public class TestScriptWithReorderableList : MonoBehaviour
{
public string standardField;
public SimpleStateMachine stateMachine;
}
[System.Serializable]
public class SimpleStateMachine
{
[SerializeField]
private int _serialId = -1;
public SimpleStateMachineState[] states = new SimpleStateMachineState[0];
}
[System.Serializable]
public class SimpleStateMachineState
{
public int id; // use this when saving current state etc.
public string name;
public override string ToString()
{
return name;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(SimpleStateMachine))]
public class SimpleStateMachineInspector : PropertyDrawer
{
private const float FIELD_PADDING = 2f;
private const string LIST_PROPERTY_NAME = "states";
private const string NAME_PROPERTY = "name";
private const string ID_PROPERTY = "id";
private const string SERIAL_ID_PROPERTY = "_serialId";
private ReorderableList _stateList;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var list = GetList(property);
list.DoList(position);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var states = GetList(property);
return states.GetHeight();
}
private ReorderableList GetList(SerializedProperty property)
{
if (_stateList == null)
{
var listProperty = property.FindPropertyRelative(LIST_PROPERTY_NAME);
_stateList = new ReorderableList(property.serializedObject, property.FindPropertyRelative(LIST_PROPERTY_NAME));
_stateList.drawHeaderCallback = (Rect rect) =>
{
EditorGUI.LabelField(rect, "States");
};
_stateList.drawElementCallback =
(Rect rect, int index, bool isActive, bool isFocused) =>
{
rect.y += FIELD_PADDING;
string name = listProperty.GetArrayElementAtIndex(index).FindPropertyRelative(NAME_PROPERTY).stringValue;
listProperty.GetArrayElementAtIndex(index).FindPropertyRelative(NAME_PROPERTY).stringValue = EditorGUI.TextField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), name);
};
_stateList.onAddCallback = (ReorderableList list) =>
{
var states = property.FindPropertyRelative(LIST_PROPERTY_NAME);
// increment serial id
int id = property.FindPropertyRelative(SERIAL_ID_PROPERTY).intValue;
id++;
property.FindPropertyRelative(SERIAL_ID_PROPERTY).intValue = id;
int length = states.arraySize;
states.InsertArrayElementAtIndex(length);
states.GetArrayElementAtIndex(length).FindPropertyRelative(ID_PROPERTY).intValue = id;
states.GetArrayElementAtIndex(length).FindPropertyRelative(NAME_PROPERTY).stringValue = "<Unnamed State>";
};
}
return _stateList;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment