TimelineImprovements

This commit is contained in:
ThomasCharester committed 2026-11-20 14:28:56 +03:00
1 parent e312131725
commit f927552adc
2211 files changed
+115416 -540944

No files matched your search

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 285cbd8c7df70446c901672504e736c2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,25 +0,0 @@
{
"name": "Alchemy.Editor",
"rootNamespace": "Alchemy.Editor",
"references": [
"GUID:88be65f96b86746888c927a5c8ff3534",
"GUID:2765e68924a08a94ea0ea66b31c0168f"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.serialization",
"expression": "",
"define": "ALCHEMY_SUPPORT_SERIALIZATION"
}
],
"noEngineReferences": false
}
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 5fd453cd0d182422093c4a764fd5eadb
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,77 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
/// <summary>
/// Base class for extending drawing processing for fields with Alchemy attributes.
/// </summary>
public abstract class AlchemyAttributeDrawer
{
SerializedObject serializedObject;
SerializedProperty serializedProperty;
object target;
MemberInfo memberInfo;
Attribute attribute;
VisualElement targetElement;
/// <summary>
/// Target serialized object.
/// </summary>
public SerializedObject SerializedObject => serializedObject;
/// <summary>
/// Target serialized property.
/// </summary>
public SerializedProperty SerializedProperty => serializedProperty;
/// <summary>
/// Target object.
/// </summary>
public object Target => target;
/// <summary>
/// MemberInfo of the target member.
/// </summary>
public MemberInfo MemberInfo => memberInfo;
/// <summary>
/// Target attribute.
/// </summary>
public Attribute Attribute => attribute;
/// <summary>
/// Target visual element.
/// </summary>
public VisualElement TargetElement => targetElement;
/// <summary>
/// Called when the target visual element is created.
/// </summary>
public abstract void OnCreateElement();
internal static void ExecutePropertyDrawers(SerializedObject serializedObject, SerializedProperty property, object target, MemberInfo memberInfo, VisualElement memberElement)
{
var attributes = memberInfo.GetCustomAttributes();
var processorTypes = TypeCache.GetTypesWithAttribute(typeof(CustomAttributeDrawerAttribute));
foreach (var attribute in attributes)
{
var processorType = processorTypes.FirstOrDefault(x => x.IsSubclassOf(typeof(AlchemyAttributeDrawer)) && x.GetCustomAttribute<CustomAttributeDrawerAttribute>().targetAttributeType == attribute.GetType());
if (processorType == null) continue;
var processor = (AlchemyAttributeDrawer)Activator.CreateInstance(processorType);
processor.serializedObject = serializedObject;
processor.serializedProperty = property;
processor.target = target;
processor.memberInfo = memberInfo;
processor.attribute = attribute;
processor.targetElement = memberElement;
processor.OnCreateElement();
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: c6e4cd4adfd574c4d8a27f6c20e60102
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,113 +0,0 @@
using System.Reflection;
using System.Linq;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Alchemy.Inspector;
#if ALCHEMY_SUPPORT_SERIALIZATION
using Alchemy.Serialization;
#endif
namespace Alchemy.Editor
{
using Editor = UnityEditor.Editor;
/// <summary>
/// Editor base class for Inspector drawing in Alchemy
/// </summary>
public abstract class AlchemyEditor : Editor
{
const string ScriptFieldName = "m_Script";
#if ALCHEMY_SUPPORT_SERIALIZATION
const string AlchemySerializationWarning = "In the current version, fields with the [AlchemySerializedField] attribute do not support editing multiple objects.";
#endif
void OnEnable()
{
foreach (var target in targets)
{
foreach (var method in ReflectionHelper.GetAllMethodsIncludingBaseNonPublic(target.GetType())
.Where(x => x.HasCustomAttribute<OnInspectorEnableAttribute>()))
{
method.Invoke(target, null);
}
}
}
void OnDisable()
{
foreach (var target in targets)
{
foreach (var method in ReflectionHelper.GetAllMethodsIncludingBaseNonPublic(target.GetType())
.Where(x => x.HasCustomAttribute<OnInspectorDisableAttribute>()))
{
method.Invoke(target, null);
}
}
}
void OnDestroy()
{
foreach (var target in targets)
{
foreach (var method in ReflectionHelper.GetAllMethodsIncludingBaseNonPublic(target.GetType())
.Where(x => x.HasCustomAttribute<OnInspectorDestroyAttribute>()))
{
method.Invoke(target, null);
}
}
}
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
var targetType = target.GetType();
if (targetType.HasCustomAttribute<DisableAlchemyEditorAttribute>())
{
// Create default inspector
InspectorElement.FillDefaultInspector(root, serializedObject, this);
return root;
}
#if ALCHEMY_SUPPORT_SERIALIZATION
if (targetType.HasCustomAttribute<AlchemySerializeAttribute>() && targets.Length > 1)
{
root.Add(new HelpBox(AlchemySerializationWarning, HelpBoxMessageType.Error));
}
#endif
// Add script field
if (targetType.GetCustomAttribute<HideScriptFieldAttribute>() == null)
{
var scriptField = new PropertyField(serializedObject.FindProperty(ScriptFieldName));
scriptField.SetEnabled(false);
root.Add(scriptField);
root.Add(new VisualElement()
{
style = { height = EditorGUIUtility.standardVerticalSpacing * 0.5f }
});
}
// Add elements
InspectorHelper.BuildElements(serializedObject, root, target, name => serializedObject.FindProperty(name));
return root;
}
}
#if !ALCHEMY_DISABLE_DEFAULT_EDITOR
[CustomEditor(typeof(MonoBehaviour), editorForChildClasses: true, isFallback = true)]
[CanEditMultipleObjects]
internal sealed class MonoBehaviourEditor : AlchemyEditor { }
[CustomEditor(typeof(ScriptableObject), editorForChildClasses: true, isFallback = true)]
[CanEditMultipleObjects]
internal sealed class ScriptableObjectEditor : AlchemyEditor { }
#endif
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 09b0ba97e97f24db4a0dce5a1e942810
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,31 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using Alchemy.Inspector;
using UnityEditor;
namespace Alchemy.Editor
{
/// <summary>
/// Alchemy Editor utility functions.
/// </summary>
public static class AlchemyEditorUtility
{
/// <summary>
/// Finds the type of drawer that corresponds to PropertyGroupAttribute.
/// </summary>
public static Type FindGroupDrawerType(PropertyGroupAttribute attribute)
{
return TypeCache.GetTypesWithAttribute<CustomGroupDrawerAttribute>()
.FirstOrDefault(x => x.GetCustomAttribute<CustomGroupDrawerAttribute>().targetAttributeType == attribute.GetType());
}
internal static AlchemyGroupDrawer CreateGroupDrawer(PropertyGroupAttribute attribute, Type targetType)
{
var drawerType = FindGroupDrawerType(attribute);
var drawer = (AlchemyGroupDrawer)Activator.CreateInstance(drawerType);
drawer.SetUniqueId("AlchemyGroupId_" + targetType.FullName + "_" + attribute.GroupPath);
return drawer;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 890788e0ea34e47319ee5f653021c4dd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,65 +0,0 @@
using System.IO;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
/// <summary>
/// Base class for constructing EditorWindow using Alchemy attributes.
/// </summary>
public abstract class AlchemyEditorWindow : EditorWindow
{
protected virtual void CreateGUI()
{
// Load data
LoadWindowData(GetWindowDataPath());
// Create root element and serialized object
var windowElement = new VisualElement();
var serializedObject = new SerializedObject(this);
// Build visual elements and bind serialized object
InspectorHelper.BuildElements(serializedObject, windowElement, this, name => serializedObject.FindProperty(name));
windowElement.Bind(serializedObject);
// Remove "Serialized Data Model Controller" field
windowElement.hierarchy.RemoveAt(0);
// Set callback
windowElement.TrackSerializedObjectValue(serializedObject, so => SaveWindowData(GetWindowDataPath()));
rootVisualElement.Add(windowElement);
}
/// <summary>
/// Gets the path where the window data is saved. The default path is $"ProjectSettings/{GetType().FullName}.json".
/// </summary>
protected virtual string GetWindowDataPath()
{
return $"ProjectSettings/{GetType().FullName}.json";
}
/// <summary>
/// Saves the current window data.
/// </summary>
/// <param name="dataPath">Window data path</param>
protected virtual void SaveWindowData(string dataPath)
{
File.WriteAllText(dataPath, JsonUtility.ToJson(this, true));
}
/// <summary>
/// Loads saved window data.
/// </summary>
/// <param name="dataPath">Window data path</param>
protected virtual void LoadWindowData(string dataPath)
{
if (File.Exists(dataPath))
{
JsonUtility.FromJsonOverwrite(File.ReadAllText(dataPath), this);
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 03f5997e2822949b0bbe12ee0a4ab1f6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,35 +0,0 @@
using System;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
/// <summary>
/// Base class for implementing Alchemy group attribute drawing process.
/// </summary>
public abstract class AlchemyGroupDrawer
{
/// <summary>
/// Create a visual element that will be the root of the group.
/// </summary>
/// <param name="label">Label text</param>
public abstract VisualElement CreateRootElement(string label);
/// <summary>
/// Returns the corresponding visual element when the root visual element differs depending on the attribute value.
/// </summary>
/// <param name="attribute">Target attribute</param>
public virtual VisualElement GetGroupElement(Attribute attribute) => null;
/// <summary>
/// ID used to identify the group.
/// </summary>
public string UniqueId => uniqueId;
string uniqueId;
internal void SetUniqueId(string id)
{
this.uniqueId = id;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6c870ede4caad4eb2accdd389ae0a436
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,132 +0,0 @@
using System.Collections.Generic;
using System.IO;
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
/// <summary>
/// Alchemy project-level settings
/// </summary>
public sealed class AlchemySettings : ScriptableObject
{
static readonly string SettingsPath = "ProjectSettings/AlchemySettings.json";
static AlchemySettings instance;
/// <summary>
/// Get a cached instance. If the cache does not exist, returns a newly created one.
/// </summary>
public static AlchemySettings GetOrCreateSettings()
{
if (instance != null) return instance;
if (File.Exists(SettingsPath))
{
instance = CreateInstance<AlchemySettings>();
JsonUtility.FromJsonOverwrite(File.ReadAllText(SettingsPath), instance);
}
else
{
instance = CreateInstance<AlchemySettings>();
}
return instance;
}
/// <summary>
/// Save the settings to a file.
/// </summary>
public static void SaveSettings()
{
File.WriteAllText(SettingsPath, JsonUtility.ToJson(instance, true));
}
static readonly string SettingsMenuName = "Project/Alchemy";
[SettingsProvider]
internal static SettingsProvider CreateSettingsProvider()
{
return new SettingsProvider(SettingsMenuName, SettingsScope.Project)
{
label = "Alchemy",
keywords = new HashSet<string>(new[] { "Alchemy, Inspector, Hierarchy" }),
guiHandler = searchContext =>
{
var serializedObject = new SerializedObject(GetOrCreateSettings());
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(10f);
using (new EditorGUILayout.VerticalScope())
{
EditorGUILayout.LabelField("Hierarchy", EditorStyles.boldLabel);
using (var changeCheck = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("hierarchyObjectMode"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("showHierarchyToggles"), new GUIContent("Show Toggles"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("showComponentIcons"));
var showTreeMap = serializedObject.FindProperty("showTreeMap");
EditorGUILayout.PropertyField(showTreeMap);
if (showTreeMap.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(serializedObject.FindProperty("treeMapColor"), new GUIContent("Color"));
EditorGUI.indentLevel--;
}
var showSeparator = serializedObject.FindProperty("showSeparator");
EditorGUILayout.PropertyField(showSeparator, new GUIContent("Show Row Separator"));
if (showSeparator.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(serializedObject.FindProperty("separatorColor"), new GUIContent("Color"));
EditorGUI.indentLevel--;
var showRowShading = serializedObject.FindProperty("showRowShading");
EditorGUILayout.PropertyField(showRowShading);
if (showRowShading.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(serializedObject.FindProperty("evenRowColor"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("oddRowColor"));
EditorGUI.indentLevel--;
}
}
if (changeCheck.changed)
{
serializedObject.ApplyModifiedProperties();
SaveSettings();
}
}
}
}
},
};
}
[SerializeField] HierarchyObjectMode hierarchyObjectMode = HierarchyObjectMode.RemoveInBuild;
[SerializeField] bool showHierarchyToggles;
[SerializeField] bool showComponentIcons;
[SerializeField] bool showTreeMap;
[SerializeField] Color treeMapColor = new(0.53f, 0.53f, 0.53f, 0.45f);
[SerializeField] bool showSeparator;
[SerializeField] bool showRowShading;
[SerializeField] Color separatorColor = new(0.19f, 0.19f, 0.19f, 0f);
[SerializeField] Color evenRowColor = new(0f, 0f, 0f, 0.07f);
[SerializeField] Color oddRowColor = Color.clear;
public HierarchyObjectMode HierarchyObjectMode => hierarchyObjectMode;
public bool ShowHierarchyToggles => showHierarchyToggles;
public bool ShowComponentIcons => showComponentIcons;
public bool ShowTreeMap => showTreeMap;
public Color TreeMapColor => treeMapColor;
public bool ShowSeparator => showSeparator;
public bool ShowRowShading => showRowShading;
public Color SeparatorColor => separatorColor;
public Color EvenRowColor => evenRowColor;
public Color OddRowColor => oddRowColor;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: be6c5afdb20ff4718b97d2eeeb1787e2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,430 +0,0 @@
using System.Linq;
using Alchemy.Editor.Elements;
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Drawers
{
[CustomAttributeDrawer(typeof(ReadOnlyAttribute))]
public sealed class ReadOnlyDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
TargetElement.SetEnabled(false);
}
}
[CustomAttributeDrawer(typeof(IndentAttribute))]
public sealed class IndentDrawer : AlchemyAttributeDrawer
{
const float IndentPadding = 15f;
public override void OnCreateElement()
{
TargetElement.RegisterCallback<GeometryChangedEvent>(x => AddPadding());
}
void AddPadding()
{
var label = TargetElement.Q<Label>();
if (label == null) return;
label.style.paddingLeft = ((IndentAttribute)Attribute).indent * IndentPadding;
}
}
[CustomAttributeDrawer(typeof(HideInPlayModeAttribute))]
public sealed class HideInPlayModeDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
TargetElement.style.display = Application.isPlaying ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(HideInEditModeAttribute))]
public sealed class HideInEditModeDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
TargetElement.style.display = !Application.isPlaying ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(DisableInPlayModeAttribute))]
public sealed class DisableInPlayModeDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
if (Application.isPlaying) TargetElement.SetEnabled(false);
}
}
[CustomAttributeDrawer(typeof(DisableInEditModeAttribute))]
public sealed class DisableInEditModeDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
if (!Application.isPlaying) TargetElement.SetEnabled(false);
}
}
[CustomAttributeDrawer(typeof(HideLabelAttribute))]
public sealed class HideLabelDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
if (TargetElement is AlchemyPropertyField field)
{
field.Label = string.Empty;
return;
}
var labelElement = TargetElement.Q<Label>();
if (labelElement == null) return;
labelElement.text = string.Empty;
}
}
[CustomAttributeDrawer(typeof(LabelTextAttribute))]
public sealed class LabelTextDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
var labelTextAttribute = (LabelTextAttribute)Attribute;
switch (TargetElement)
{
case AlchemyPropertyField alchemyPropertyField:
alchemyPropertyField.Label = labelTextAttribute.Text;
break;
case MethodButton methodButton:
methodButton.SetLableText(labelTextAttribute.Text);
break;
case Button button:
button.text = labelTextAttribute.Text;
break;
default:
var labelElement = TargetElement.Q<Label>();
if (labelElement == null) return;
labelElement.text = labelTextAttribute.Text;
break;
}
}
}
[CustomAttributeDrawer(typeof(LabelWidthAttribute))]
public sealed class LabelWidthDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
var width = ((LabelWidthAttribute)Attribute).Width;
if (TargetElement is AlchemyPropertyField field && field.FieldElement is PropertyField)
{
var executed = false;
field.schedule.Execute(() =>
{
var label = field.Q<Label>();
if (label == null) return;
GUIHelper.SetMinAndCurrentWidth(label, width);
executed = true;
}).Until(() => executed);
return;
}
Debug.LogWarning("The LabelWidth attribute currently only supports PropertyField and is ignored for other visual elements.");
}
}
[CustomAttributeDrawer(typeof(HideIfAttribute))]
public sealed class HideIfDrawer : TrackSerializedObjectAttributeDrawer
{
protected override void OnInspectorChanged()
{
var condition = ReflectionHelper.GetValueBool(Target, ((HideIfAttribute)Attribute).Condition);
TargetElement.style.display = condition ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(ShowIfAttribute))]
public sealed class ShowIfDrawer : TrackSerializedObjectAttributeDrawer
{
protected override void OnInspectorChanged()
{
var condition = ReflectionHelper.GetValueBool(Target, ((ShowIfAttribute)Attribute).Condition);
TargetElement.style.display = !condition ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(DisableIfAttribute))]
public sealed class DisableIfDrawer : TrackSerializedObjectAttributeDrawer
{
protected override void OnInspectorChanged()
{
var condition = ReflectionHelper.GetValueBool(Target, ((DisableIfAttribute)Attribute).Condition);
TargetElement.SetEnabled(!condition);
}
}
[CustomAttributeDrawer(typeof(EnableIfAttribute))]
public sealed class EnableIfDrawer : TrackSerializedObjectAttributeDrawer
{
protected override void OnInspectorChanged()
{
var condition = ReflectionHelper.GetValueBool(Target, ((EnableIfAttribute)Attribute).Condition);
TargetElement.SetEnabled(condition);
}
}
[CustomAttributeDrawer(typeof(RequiredAttribute))]
public sealed class RequiredDrawer : TrackSerializedObjectAttributeDrawer
{
HelpBox helpBox;
public override void OnCreateElement()
{
if (SerializedProperty == null || SerializedProperty.propertyType != SerializedPropertyType.ObjectReference) return;
var message = ((RequiredAttribute)Attribute).Message ?? ObjectNames.NicifyVariableName(SerializedProperty.displayName) + " is required.";
helpBox = new HelpBox(message, HelpBoxMessageType.Error);
var parent = TargetElement.parent;
parent.Insert(parent.IndexOf(TargetElement), helpBox);
base.OnCreateElement();
}
protected override void OnInspectorChanged()
{
helpBox.style.display = SerializedProperty.objectReferenceValue != null ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(ValidateInputAttribute))]
public sealed class ValidateInputDrawer : TrackSerializedObjectAttributeDrawer
{
HelpBox helpBox;
public override void OnCreateElement()
{
if (SerializedProperty == null) return;
var message = ((ValidateInputAttribute)Attribute).Message ?? ObjectNames.NicifyVariableName(SerializedProperty.displayName) + " is not valid.";
helpBox = new HelpBox(message, HelpBoxMessageType.Error);
var parent = TargetElement.parent;
parent.Insert(parent.IndexOf(TargetElement), helpBox);
base.OnCreateElement();
}
protected override void OnInspectorChanged()
{
var result = ReflectionHelper.Invoke(Target, ((ValidateInputAttribute)Attribute).Condition, SerializedProperty.GetValue<object>());
helpBox.style.display = result is bool flag && flag ? DisplayStyle.None : DisplayStyle.Flex;
}
}
[CustomAttributeDrawer(typeof(HelpBoxAttribute))]
public sealed class HelpBoxDrawer : AlchemyAttributeDrawer
{
HelpBox helpBox;
public override void OnCreateElement()
{
var att = (HelpBoxAttribute)Attribute;
helpBox = new HelpBox(att.Message, att.MessageType);
var parent = TargetElement.parent;
parent.Insert(parent.IndexOf(TargetElement), helpBox);
}
}
[CustomAttributeDrawer(typeof(PreviewAttribute))]
public sealed class PreviewDrawer : TrackSerializedObjectAttributeDrawer
{
private Image image;
private const float BorderWidth = 1f;
private static readonly Color borderColor = new Color(0f, 0f, 0f, 0.3f);
public override void OnCreateElement()
{
if (SerializedProperty == null || SerializedProperty.propertyType != SerializedPropertyType.ObjectReference) return;
var att = (PreviewAttribute)Attribute;
image = new Image
{
scaleMode = ScaleMode.ScaleToFit,
style = {
width = att.Size,
height = att.Size,
marginTop = EditorGUIUtility.standardVerticalSpacing,
marginBottom = EditorGUIUtility.standardVerticalSpacing * 4f,
alignSelf = att.AlignStyle,
borderTopWidth = BorderWidth,
borderBottomWidth = BorderWidth,
borderLeftWidth = BorderWidth,
borderRightWidth = BorderWidth,
borderBottomColor = borderColor,
borderTopColor = borderColor,
borderLeftColor = borderColor,
borderRightColor = borderColor,
}
};
image.RegisterCallback<MouseDownEvent>(x =>
{
using var mouseDownEvent = MouseDownEvent.GetPooled(x);
var objectFieldSelector = TargetElement.Q(className: "unity-object-field__selector");
mouseDownEvent.target = objectFieldSelector;
objectFieldSelector.SendEvent(mouseDownEvent);
});
var parent = TargetElement.parent;
parent.Insert(parent.IndexOf(TargetElement) + 1, image);
base.OnCreateElement();
}
protected override void OnInspectorChanged()
{
if (SerializedProperty.objectReferenceValue == null)
{
image.image = null;
return;
}
TargetElement.schedule.Execute(() =>
{
var texture = AssetPreview.GetAssetPreview(SerializedProperty.objectReferenceValue);
image.image = texture;
}).Until(() => image.image != null);
}
}
[CustomAttributeDrawer(typeof(HorizontalLineAttribute))]
public sealed class HorizontalLineDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
var att = (HorizontalLineAttribute)Attribute;
var parent = TargetElement.parent;
var lineColor = att.Color == default ? GUIHelper.LineColor : att.Color;
var line = GUIHelper.CreateLine(lineColor, EditorGUIUtility.standardVerticalSpacing * 4f);
parent.Insert(parent.IndexOf(TargetElement), line);
}
}
[CustomAttributeDrawer(typeof(TitleAttribute))]
public sealed class TitleDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
var att = (TitleAttribute)Attribute;
var parent = TargetElement.parent;
var title = new Label(att.TitleText)
{
style = {
unityFontStyleAndWeight = FontStyle.Bold,
paddingLeft = 3f,
marginTop = 4f,
marginBottom = -2f
}
};
parent.Insert(parent.IndexOf(TargetElement), title);
if (att.SubtitleText != null)
{
var subtitle = new Label(att.SubtitleText)
{
style = {
fontSize = 10f,
paddingLeft = 4.5f,
marginTop = 1.5f,
color = GUIHelper.SubtitleColor,
unityTextAlign = TextAnchor.MiddleLeft
}
};
parent.Insert(parent.IndexOf(TargetElement), subtitle);
}
var line = GUIHelper.CreateLine(GUIHelper.LineColor, EditorGUIUtility.standardVerticalSpacing * 3f);
parent.Insert(parent.IndexOf(TargetElement), line);
}
}
[CustomAttributeDrawer(typeof(BlockquoteAttribute))]
public sealed class BlockquoteDrawer : AlchemyAttributeDrawer
{
public BlockquoteDrawer()
{
textStyle = EditorStyles.label;
textStyle.wordWrap = true;
}
readonly GUIStyle textStyle;
public override void OnCreateElement()
{
var att = (BlockquoteAttribute)Attribute;
var blockquote = new IMGUIContainer(() =>
{
var width = EditorGUIUtility.currentViewWidth;
var labelContent = new GUIContent(att.Text);
var labelHeight = textStyle.CalcHeight(labelContent, width - 3f);
var position = EditorGUILayout.GetControlRect(false, labelHeight + EditorGUIUtility.standardVerticalSpacing * 2f);
var blockRect = position;
var backgroundColor = GUIHelper.TextColor;
backgroundColor.a = 0.06f;
EditorGUI.DrawRect(blockRect, backgroundColor);
blockRect.x = position.xMin;
blockRect.width = 3;
EditorGUI.DrawRect(blockRect, GUIHelper.TextColor);
var labelPosition = position;
labelPosition.xMin += 7f;
EditorGUI.LabelField(labelPosition, labelContent, textStyle);
});
var parent = TargetElement.parent;
parent.Insert(parent.IndexOf(TargetElement), blockquote);
}
}
[CustomAttributeDrawer(typeof(OnValueChangedAttribute))]
public sealed class OnValueChangedDrawer : AlchemyAttributeDrawer
{
public override void OnCreateElement()
{
TargetElement.TrackPropertyValue(SerializedProperty, property =>
{
var methodName = ((OnValueChangedAttribute)Attribute).MethodName;
var methods = ReflectionHelper.GetAllMethodsIncludingBaseNonPublic(Target.GetType())
.Where(x => x.Name == methodName);
foreach (var methodInfo in methods)
{
if (methodInfo.Name != methodName) continue;
var parameters = methodInfo.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(property.GetPropertyType()))
{
methodInfo.Invoke(Target, new object[] { property.GetValue<object>() });
}
else if (parameters.Length == 0)
{
methodInfo.Invoke(Target, null);
}
}
});
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 82c33c1d3a21f4e9a9e57fa46d4900aa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,233 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Alchemy.Editor.Elements;
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Drawers
{
[CustomGroupDrawer(typeof(GroupAttribute))]
public sealed class GroupDrawer : AlchemyGroupDrawer
{
public override VisualElement CreateRootElement(string label)
{
return new Box()
{
style = {
width = Length.Percent(100f),
marginTop = 3f,
paddingBottom = 2f,
paddingRight = 1f,
paddingLeft = 1f,
}
};
}
}
[CustomGroupDrawer(typeof(BoxGroupAttribute))]
public sealed class BoxGroupDrawer : AlchemyGroupDrawer
{
public override VisualElement CreateRootElement(string label)
{
var helpBox = new HelpBox()
{
text = label,
style = {
flexDirection = FlexDirection.Column,
width = Length.Percent(100f),
marginTop = 3f,
paddingBottom = 3f,
paddingRight = 3f,
paddingLeft = 3f,
}
};
var labelElement = helpBox.Q<Label>();
labelElement.style.top = 2f;
labelElement.style.left = 2f;
labelElement.style.fontSize = 12f;
labelElement.style.minHeight = EditorGUIUtility.singleLineHeight;
labelElement.style.unityFontStyleAndWeight = FontStyle.Bold;
labelElement.style.alignSelf = Align.Stretch;
return helpBox;
}
}
[CustomGroupDrawer(typeof(TabGroupAttribute))]
public sealed class TabGroupDrawer : AlchemyGroupDrawer
{
VisualElement rootElement;
readonly Dictionary<string, VisualElement> tabElements = new();
string[] keyArrayCache = new string[0];
int tabIndex;
int prevTabIndex;
sealed class TabItem
{
public string name;
public VisualElement element;
}
public override VisualElement CreateRootElement(string label)
{
var configKey = UniqueId + "_TabGroup";
int.TryParse(EditorUserSettings.GetConfigValue(configKey), out tabIndex);
prevTabIndex = tabIndex;
rootElement = new HelpBox()
{
style = {
flexDirection = FlexDirection.Column,
width = Length.Percent(100f),
marginTop = 3f,
paddingBottom = 3f,
paddingRight = 3f,
paddingLeft = 3f,
}
};
rootElement.Q<Label>()?.RemoveFromHierarchy();
var tabGUIElement = new IMGUIContainer(() =>
{
var rect = EditorGUILayout.GetControlRect();
rect.xMin -= 3.7f;
rect.xMax += 3.7f;
rect.yMin -= 3.7f;
rect.yMax -= 1f;
tabIndex = GUI.Toolbar(rect, tabIndex, keyArrayCache);
if (tabIndex != prevTabIndex)
{
EditorUserSettings.SetConfigValue(configKey, tabIndex.ToString());
prevTabIndex = tabIndex;
}
foreach (var kv in tabElements)
{
kv.Value.style.display = keyArrayCache[tabIndex] == kv.Key ? DisplayStyle.Flex : DisplayStyle.None;
}
})
{
style = {
width = Length.Percent(100f),
marginLeft = 0f,
marginRight = 0f,
marginTop = 0f
}
};
rootElement.Add(tabGUIElement);
return rootElement;
}
public override VisualElement GetGroupElement(Attribute attribute)
{
var tabGroupAttribute = (TabGroupAttribute)attribute;
var tabName = tabGroupAttribute.TabName;
if (!tabElements.TryGetValue(tabName, out var element))
{
element = new VisualElement()
{
style = {
width = Length.Percent(100f)
}
};
rootElement.Add(element);
tabElements.Add(tabName, element);
keyArrayCache = tabElements.Keys.ToArray();
}
return element;
}
}
[CustomGroupDrawer(typeof(FoldoutGroupAttribute))]
public sealed class FoldoutGroupDrawer : AlchemyGroupDrawer
{
public override VisualElement CreateRootElement(string label)
{
var configKey = UniqueId + "_FoldoutGroup";
bool.TryParse(EditorUserSettings.GetConfigValue(configKey), out var result);
var foldout = new Foldout()
{
style = {
width = Length.Percent(100f)
},
text = label,
value = result
};
foldout.RegisterValueChangedCallback(x =>
{
EditorUserSettings.SetConfigValue(configKey, x.newValue.ToString());
});
return foldout;
}
}
[CustomGroupDrawer(typeof(HorizontalGroupAttribute))]
public sealed class HorizontalGroupDrawer : AlchemyGroupDrawer
{
public override VisualElement CreateRootElement(string label)
{
var root = new VisualElement()
{
style = {
width = Length.Percent(100f),
flexDirection = FlexDirection.Row
}
};
static void AdjustLabel(PropertyField element, VisualElement inspector, int childCount)
{
if (element.childCount == 0) return;
if (element.Q<Foldout>() != null) return;
var field = element[0];
field.RemoveFromClassList("unity-base-field__aligned");
var labelElement = field.Q<Label>();
if (labelElement != null)
{
labelElement.style.minWidth = 0f;
labelElement.style.width = GUIHelper.CalculateLabelWidth(element, inspector) * 0.8f / childCount;
}
}
root.schedule.Execute(() =>
{
if (root.childCount <= 1) return;
var visualTree = root.panel.visualTree;
foreach (var field in root.Query<PropertyField>().Build())
{
AdjustLabel(field, visualTree, root.childCount);
}
foreach (var field in root.Query<GenericField>().Children<PropertyField>().Build())
{
AdjustLabel(field, visualTree, root.childCount);
}
});
return root;
}
}
[CustomGroupDrawer(typeof(InlineGroupAttribute))]
public sealed class InlineGroupDrawer : AlchemyGroupDrawer
{
public override VisualElement CreateRootElement(string label)
{
return new VisualElement();
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: fa0ce00655a224efd9ed552633ccd715
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,19 +0,0 @@
using System;
namespace Alchemy.Editor
{
/// <summary>
/// Attribute for specifying the target attribute of AlchemyAttributeDrawer.
/// </summary>
public sealed class CustomAttributeDrawerAttribute : Attribute
{
public CustomAttributeDrawerAttribute(Type targetAttributeType, int order = 0)
{
this.targetAttributeType = targetAttributeType;
this.order = order;
}
public readonly Type targetAttributeType;
public readonly int order;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e5369cccdbb3a47c0ac7e5fcff993276
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,17 +0,0 @@
using System;
namespace Alchemy.Editor
{
/// <summary>
/// Attribute for specifying the target attribute of AlchemyGroupDrawer.
/// </summary>
public sealed class CustomGroupDrawerAttribute : Attribute
{
public CustomGroupDrawerAttribute(Type targetAttributeType)
{
this.targetAttributeType = targetAttributeType;
}
public readonly Type targetAttributeType;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: f0c6d37c5a83b4eef8f5359c67329e56
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 4dc283a9b881942e6bcea33ae81ca853
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,115 +0,0 @@
using System;
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Visual Element that draws properties based on Alchemy attributes
/// </summary>
public sealed class AlchemyPropertyField : BindableElement
{
public AlchemyPropertyField(SerializedProperty property, Type type, bool isArrayElement = false)
{
var labelText = ObjectNames.NicifyVariableName(property.displayName);
switch (property.propertyType)
{
// NOTE: RectOffset is a generic property type, but it doesn't have a SerializeField. Instead, use PropertyField.
case SerializedPropertyType.Generic when property.type == "RectOffset":
default:
element = new PropertyField(property);
break;
case SerializedPropertyType.ObjectReference:
if (property.GetAttribute<InlineEditorAttribute>() != null)
{
element = new InlineEditorObjectField(property, type);
}
else
{
element = GUIHelper.CreateObjectPropertyField(property, type);
}
break;
case SerializedPropertyType.Generic:
var targetType = property.GetPropertyType(isArrayElement);
var isManagedReferenceProperty = property.propertyType == SerializedPropertyType.ManagedReference;
if (InternalAPIHelper.GetDrawerTypeForType(targetType, isManagedReferenceProperty) != null)
{
element = new PropertyField(property);
}
else if (property.isArray)
{
element = new PropertyListView(property);
}
else if (targetType.TryGetCustomAttribute<PropertyGroupAttribute>(out var groupAttribute)) // custom group
{
var drawer = AlchemyEditorUtility.CreateGroupDrawer(groupAttribute, targetType);
var root = drawer.CreateRootElement(labelText);
InspectorHelper.BuildElements(property.serializedObject, root, property.GetValue<object>(), name => property.FindPropertyRelative(name));
if (root is BindableElement bindableElement) bindableElement.BindProperty(property);
element = root;
}
else
{
var foldout = new Foldout() { text = labelText };
var clickable = InternalAPIHelper.GetClickable(foldout.Q<Toggle>());
InternalAPIHelper.SetAcceptClicksIfDisabled(clickable, true);
InspectorHelper.BuildElements(property.serializedObject, foldout, property.GetValue<object>(), name => property.FindPropertyRelative(name));
foldout.BindProperty(property);
element = foldout;
}
break;
case SerializedPropertyType.ManagedReference:
element = new SerializeReferenceField(property);
break;
}
Add(element);
}
readonly VisualElement element;
public VisualElement FieldElement => element;
public string Label
{
get
{
return element switch
{
Foldout foldout => foldout.text,
PropertyField propertyField => propertyField.label,
SerializeReferenceField serializeReferenceField => serializeReferenceField.foldout.text,
InlineEditorObjectField inlineEditorObjectField => inlineEditorObjectField.Label,
PropertyListView propertyListView => propertyListView.Label,
_ => null,
};
}
set
{
switch (element)
{
case Foldout foldout:
foldout.text = value;
break;
case PropertyField propertyField:
propertyField.label = value;
break;
case SerializeReferenceField serializeReferenceField:
serializeReferenceField.foldout.text = value;
break;
case InlineEditorObjectField inlineEditorObjectField:
inlineEditorObjectField.Label = value;
break;
case PropertyListView propertyListView:
propertyListView.Label = value;
break;
}
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 90a3b3c6a5e434218b95ca18fd032a79
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,63 +0,0 @@
using System;
using System.Reflection;
using Alchemy.Inspector;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public sealed class ClassField : VisualElement
{
public ClassField(Type type, string label) : this(TypeHelper.CreateDefaultInstance(type), type, label) { }
public ClassField(object obj, Type type, string label)
{
var foldout = new Foldout
{
text = label,
value = false
};
var toggle = foldout.Q<Toggle>();
var clickable = InternalAPIHelper.GetClickable(toggle);
InternalAPIHelper.SetAcceptClicksIfDisabled(clickable, true);
// Build node
var rootNode = InspectorHelper.BuildInspectorNode(type);
// Add elements
foreach (var node in rootNode.DescendantsAndSelf())
{
// Get or create group element
if (node.Parent == null)
{
node.VisualElement = foldout;
}
else if (node.Drawer == null)
{
node.VisualElement = node.Parent.VisualElement;
}
else
{
node.VisualElement = node.Drawer.CreateRootElement(node.Name);
node.Parent.VisualElement.Add(node.VisualElement);
}
// Add member elements
foreach (var member in node.Members.OrderByAttributeThenByMemberType())
{
var element = new ReflectionField(obj, member);
element.style.width = Length.Percent(100f);
element.OnValueChanged += x => OnValueChanged?.Invoke(obj);
var e = node.Drawer?.GetGroupElement(member.GetCustomAttribute<PropertyGroupAttribute>());
if (e == null) node.VisualElement.Add(element);
else e.Add(element);
AlchemyAttributeDrawer.ExecutePropertyDrawers(null, null, obj, member, element);
}
}
Add(foldout);
}
public event Action<object> OnValueChanged;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6b645f1746ed04e3dbb48f5e2568f401
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,167 +0,0 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public sealed class DictionaryField : HashMapFieldBase
{
public DictionaryField(object collection, string label) : base(collection, label)
{
if (collection != null)
{
keyType = collection.GetType().GenericTypeArguments[0];
valueType = collection.GetType().GenericTypeArguments[1];
kvType = typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType);
}
}
public override string CollectionTypeName => TypeName;
const string TypeName = "Dictionary";
const string KeyName = "Key";
const string ValueName = "Value";
readonly Type keyType;
readonly Type valueType;
readonly Type kvType;
public override bool CheckElement(object element)
{
var keyObj = ReflectionHelper.GetPropertyValue(element, element.GetType(), KeyName);
if (keyObj is string str && string.IsNullOrEmpty(str)) return true;
if (keyObj == null) return true;
return (bool)ReflectionHelper.Invoke(Collection, "ContainsKey", keyObj);
}
public override object CreateElement()
{
var keyObj = TypeHelper.CreateDefaultInstance(keyType);
var valueObj = TypeHelper.CreateDefaultInstance(valueType);
return Activator.CreateInstance(kvType, keyObj, valueObj);
}
public override void AddElement(object element)
{
var keyObj = ReflectionHelper.GetPropertyValue(element, kvType, KeyName);
var valueObj = ReflectionHelper.GetPropertyValue(element, kvType, ValueName);
ReflectionHelper.Invoke(Collection, "Add", keyObj, valueObj);
}
public override bool RemoveElement(object element)
{
return (bool)ReflectionHelper.Invoke(Collection, "Remove", ReflectionHelper.GetPropertyValue(element, kvType, KeyName));
}
public override void ClearElements()
{
ReflectionHelper.Invoke(Collection, "Clear");
}
public override HashMapItemBase CreateItem(object collection, object elementObj, string label)
{
return new Item(collection, elementObj);
}
public sealed class Item : HashMapItemBase
{
public Item(object collection, object keyValuePair)
{
var box = new Box()
{
style = {
marginBottom = 3.5f,
marginRight = -2f,
flexDirection = FlexDirection.Row
}
};
kvType = keyValuePair.GetType();
var keyType = kvType.GenericTypeArguments[0];
var valueType = kvType.GenericTypeArguments[1];
key = ReflectionHelper.GetPropertyValue(keyValuePair, kvType, KeyName);
value = ReflectionHelper.GetPropertyValue(keyValuePair, kvType, ValueName);
this.collection = collection;
this.keyValuePair = keyValuePair;
var keyValueElement = new VisualElement()
{
style = {
flexDirection = FlexDirection.Column,
flexGrow = 1f
}
};
box.Add(keyValueElement);
keyField = new GenericField(key, keyType, KeyName)
{
style = { flexGrow = 1f }
};
keyField.OnValueChanged += SetKey;
keyValueElement.Add(keyField);
valueField = new GenericField(value, valueType, ValueName)
{
style = { flexGrow = 1f }
};
valueField.OnValueChanged += SetValue;
keyValueElement.Add(valueField);
var closeButton = new Button(() => OnClose?.Invoke())
{
style = {
width = EditorGUIUtility.singleLineHeight,
height = EditorGUIUtility.singleLineHeight,
unityFontStyleAndWeight = FontStyle.Bold,
fontSize = 10f
},
text = "X",
};
box.Add(closeButton);
Add(box);
}
readonly GenericField keyField;
readonly GenericField valueField;
readonly object collection;
public override object Value => keyValuePair;
object key;
object value;
object keyValuePair;
readonly Type kvType;
public override void Lock()
{
keyField.SetEnabled(false);
valueField.OnValueChanged -= SetValue;
valueField.OnValueChanged += x =>
{
value = x;
keyValuePair = Activator.CreateInstance(kvType, key, value);
ReflectionHelper.GetProperty(collection.GetType(), "Item").SetValue(collection, value, new object[] { key });
OnValueChanged?.Invoke(keyValuePair);
};
}
void SetKey(object obj)
{
key = obj;
keyValuePair = Activator.CreateInstance(kvType, key, value);
OnValueChanged?.Invoke(keyValuePair);
}
void SetValue(object obj)
{
value = obj;
keyValuePair = Activator.CreateInstance(kvType, key, value);
OnValueChanged?.Invoke(keyValuePair);
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ef13233afbf8a44f68f8641b03e2303f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,341 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Visual Element that creates a suitable input Field from object type
/// </summary>
public sealed class GenericField : VisualElement
{
const string CreateButtonText = "Create...";
public GenericField(object obj, Type type, string label, bool isDelayed = false)
{
Build(obj, type, label, isDelayed);
GUIHelper.ScheduleAdjustLabelWidth(this);
}
void Build(object obj, Type type, string label, bool isDelayed)
{
Clear();
// Add [Create...] button
if (obj == null && !typeof(UnityEngine.Object).IsAssignableFrom(type))
{
var nullLabelElement = new VisualElement()
{
style = {
width = Length.Percent(100f),
height = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing,
paddingLeft = 3f,
flexDirection = FlexDirection.Row
}
};
nullLabelElement.Add(new Label(label + " (Null)")
{
style = {
flexGrow = 1f,
unityTextAlign = TextAnchor.MiddleLeft
}
});
// TODO: support polymorphism
if (type == typeof(string))
{
nullLabelElement.Add(new Button(() =>
{
var instance = "";
Build(instance, type, label, isDelayed);
OnValueChanged?.Invoke(instance);
})
{
text = CreateButtonText
});
}
else if (type.IsArray && type.GetArrayRank() == 1)
{
nullLabelElement.Add(new Button(() =>
{
var instance = Array.CreateInstance(type.GetElementType(), 0);
Build(instance, type, label, isDelayed);
OnValueChanged?.Invoke(instance);
})
{
text = CreateButtonText
});
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) // nullable
{
nullLabelElement.Add(new Button(() =>
{
var instance = Activator.CreateInstance(type, Activator.CreateInstance(type.GenericTypeArguments[0]));
Build(instance, type, label, isDelayed);
OnValueChanged?.Invoke(instance);
})
{
text = CreateButtonText
});
}
else if (TypeHelper.HasDefaultConstructor(type))
{
nullLabelElement.Add(new Button(() =>
{
var instance = TypeHelper.CreateDefaultInstance(type);
Build(instance, type, label, isDelayed);
OnValueChanged?.Invoke(instance);
})
{
text = CreateButtonText
});
}
Add(nullLabelElement);
return;
}
this.isDelayed = isDelayed;
if (type == typeof(bool))
{
AddField(new Toggle(label), (bool)obj);
}
else if (type == typeof(int))
{
AddField(new IntegerField(label), (int)obj);
}
else if (type == typeof(sbyte))
{
AddSmallIntegerField(label, (sbyte)obj, sbyte.MinValue, sbyte.MaxValue, x => (sbyte)x);
}
else if (type == typeof(byte))
{
AddSmallIntegerField(label, (byte)obj, byte.MinValue, byte.MaxValue, x => (byte)x);
}
else if (type == typeof(short))
{
AddSmallIntegerField(label, (short)obj, short.MinValue, short.MaxValue, x => (short)x);
}
else if (type == typeof(ushort))
{
AddSmallIntegerField(label, (ushort)obj, ushort.MinValue, ushort.MaxValue, x => (ushort)x);
}
else if (type == typeof(uint))
{
#if UNITY_2022_1_OR_NEWER
AddField(new UnsignedIntegerField(label), (uint)obj);
#else
var value = (uint)obj;
var control = new LongField(label);
control.value = value;
control.RegisterValueChangedCallback(x =>
{
var newValue = (uint)Math.Clamp(control.value, 0, uint.MaxValue);
OnValueChanged?.Invoke(newValue);
control.value = newValue;
});
Add(control);
#endif
}
else if (type == typeof(long))
{
AddField(new LongField(label), (long)obj);
}
else if (type == typeof(ulong))
{
#if UNITY_2022_1_OR_NEWER
AddField(new UnsignedLongField(label), (ulong)obj);
#else
var value = (ulong)obj;
var control = new LongField(label);
control.value = (long)value;
control.RegisterValueChangedCallback(x =>
{
var newValue = Math.Clamp(control.value, 0, long.MaxValue);
OnValueChanged?.Invoke((ulong)newValue);
control.value = newValue;
});
Add(control);
#endif
}
else if (type == typeof(float))
{
AddField(new FloatField(label), (float)obj);
}
else if (type == typeof(double) || type == typeof(decimal))
{
AddField(new DoubleField(label), (double)obj);
}
else if (type == typeof(string))
{
AddField(new TextField(label), (string)obj);
}
else if (type == typeof(char))
{
var charField = new TextField(label, 1, false, false, default) { value = obj.ToString() };
charField.RegisterValueChangedCallback(x =>
{
if (string.IsNullOrEmpty(x.newValue)) return;
OnValueChanged?.Invoke(x.newValue[0]);
});
Add(charField);
}
else if (type.IsEnum)
{
var value = (Enum)obj;
if (value.GetType().HasCustomAttribute<FlagsAttribute>()) AddField(new EnumFlagsField(label, value), value);
else AddField(new EnumField(label, value), value);
}
else if (type == typeof(Vector2))
{
AddField(new Vector2Field(label), (Vector2)obj);
}
else if (type == typeof(Vector2Int))
{
AddField(new Vector2IntField(label), (Vector2Int)obj);
}
else if (type == typeof(Vector3))
{
AddField(new Vector3Field(label), (Vector3)obj);
}
else if (type == typeof(Vector3Int))
{
AddField(new Vector3IntField(label), (Vector3Int)obj);
}
else if (type == typeof(Vector4))
{
AddField(new Vector4Field(label), (Vector4)obj);
}
else if (type == typeof(Rect))
{
AddField(new RectField(label), (Rect)obj);
}
else if (type == typeof(RectInt))
{
AddField(new RectIntField(label), (RectInt)obj);
}
else if (type == typeof(Bounds))
{
AddField(new BoundsField(label), (Bounds)obj);
}
else if (type == typeof(BoundsInt))
{
AddField(new BoundsIntField(label), (BoundsInt)obj);
}
else if (type == typeof(Color))
{
AddField(new ColorField(label), (Color)obj);
}
else if (type == typeof(Gradient))
{
AddField(new GradientField(label), (Gradient)obj);
}
else if (type == typeof(Hash128))
{
AddField(new Hash128Field(label), (Hash128)obj);
}
else if (type == typeof(AnimationCurve))
{
AddField(new CurveField(label), (AnimationCurve)obj);
}
else if (type == typeof(Gradient))
{
AddField(new GradientField(label), (Gradient)obj);
}
else if (typeof(UnityEngine.Object).IsAssignableFrom(type))
{
AddField(new ObjectField(label) { objectType = type }, (UnityEngine.Object)obj);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(HashSet<>))
{
var field = new HashSetField(obj, label);
field.OnValueChanged += x => OnValueChanged?.Invoke(x);
Add(field);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
var field = new DictionaryField(obj, label);
field.OnValueChanged += x => OnValueChanged?.Invoke(x);
Add(field);
}
else if (typeof(IList).IsAssignableFrom(type))
{
var field = new ListField((IList)obj, label);
field.OnValueChanged += x => OnValueChanged?.Invoke(x);
Add(field);
}
else
{
var field = new ClassField(obj, type, label);
field.OnValueChanged += x => OnValueChanged?.Invoke(x);
Add(field);
}
}
public event Action<object> OnValueChanged;
bool isDelayed;
bool changed;
void AddSmallIntegerField<T>(string label, int value, int minValue, int maxValue, Func<int, T> convert)
{
var control = new IntegerField(label) { value = value };
control.RegisterValueChangedCallback(x =>
{
var newValue = Math.Clamp(x.newValue, minValue, maxValue);
control.SetValueWithoutNotify(newValue);
if (isDelayed)
{
changed = true;
}
else
{
OnValueChanged?.Invoke(convert(newValue));
}
});
if (isDelayed)
{
control.RegisterCallback<FocusOutEvent>(_ =>
{
if (!changed) return;
OnValueChanged?.Invoke(convert(control.value));
changed = false;
});
}
Add(control);
}
void AddField<T>(BaseField<T> control, T value)
{
control.value = value;
if (isDelayed && control is not ObjectField) // ignore ObjectField
{
control.RegisterValueChangedCallback(x => changed = true);
control.RegisterCallback<FocusOutEvent>(x =>
{
if (changed)
{
OnValueChanged?.Invoke(control.value);
changed = false;
}
});
}
else
{
control.RegisterValueChangedCallback(x => OnValueChanged?.Invoke(x.newValue));
}
Add(control);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 5d48be02c25cf4bc0be72b50cae0a0c7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,170 +0,0 @@
using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public abstract class HashMapFieldBase : VisualElement
{
public HashMapFieldBase(object collection, string label)
{
this.collection = collection;
var foldout = new Foldout()
{
text = label
};
Add(foldout);
foldout.Q<Label>().style.unityFontStyleAndWeight = FontStyle.Bold;
contents = new();
foldout.Add(contents);
inputForm = new();
foldout.Add(inputForm);
addButton = new Button(() =>
{
if (isInputting) EndInput();
else StartInput();
})
{
style = {
alignSelf = Align.FlexEnd,
minWidth = 60f
},
text = "+ Add"
};
foldout.Add(addButton);
foldout.Add(new VisualElement() { style = { minHeight = 4f } });
Rebuild();
}
readonly VisualElement inputForm;
readonly VisualElement contents;
readonly Button addButton;
public object Collection => collection;
readonly object collection;
bool isInputting;
public event Action<object> OnValueChanged;
public void RegisterOnValueChangedCallback(Action<object> callback)
{
OnValueChanged += callback;
}
void StartInput()
{
void ValidateValue(object x)
{
var contains = CheckElement(x);
addButton.SetEnabled(!contains);
addButton.text = contains ? "(Invalid key)" : "Done";
}
if (isInputting) return;
isInputting = true;
var initValue = CreateElement();
var form = CreateItem(collection, initValue, "New Value");
inputForm.Clear();
inputForm.Add(form);
form.OnValueChanged += ValidateValue;
form.OnClose += () =>
{
CancelInput();
};
ValidateValue(initValue);
}
void EndInput()
{
if (!isInputting) return;
isInputting = false;
addButton.text = "+ Add";
addButton.SetEnabled(true);
AddElement(inputForm.Q<HashMapItemBase>().Value);
OnValueChanged?.Invoke(collection);
Rebuild();
}
void CancelInput()
{
isInputting = false;
addButton.text = "+ Add";
addButton.SetEnabled(true);
Rebuild();
}
// Rebuild GUI contents
public void Rebuild()
{
contents.Clear();
inputForm.Clear();
if (collection == null) return;
var i = 0;
foreach (var item in (IEnumerable)collection)
{
var element = CreateItem(collection, item, "Element " + i);
element.OnValueChanged += _ => OnValueChanged?.Invoke(collection);
element.OnClose += () =>
{
if (isInputting) return;
var remove = RemoveElement(item);
if (remove)
{
OnValueChanged?.Invoke(collection);
Rebuild();
}
};
element.Lock();
contents.Add(element);
i++;
}
if (i == 0)
{
var box = new Box();
box.style.minHeight = EditorGUIUtility.singleLineHeight * 1.2f;
box.style.paddingLeft = 6f;
var label = new Label(CollectionTypeName + " is empty.");
label.style.height = Length.Percent(100f);
label.style.unityTextAlign = TextAnchor.MiddleLeft;
box.Add(label);
inputForm.Add(box);
}
}
public abstract HashMapItemBase CreateItem(object collection, object elementObj, string label);
public abstract bool CheckElement(object element);
public abstract object CreateElement();
public abstract void AddElement(object element);
public abstract bool RemoveElement(object element);
public abstract void ClearElements();
public abstract string CollectionTypeName { get; }
public abstract class HashMapItemBase : VisualElement
{
public Action OnClose;
public Action<object> OnValueChanged;
public abstract object Value { get; }
public abstract void Lock();
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4458165df128342d3a2a50b74dcc8c47
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,92 +0,0 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public sealed class HashSetField : HashMapFieldBase
{
public HashSetField(object collection, string label) : base(collection, label) { }
public override string CollectionTypeName => "HashSet";
public override bool CheckElement(object key)
{
return (bool)ReflectionHelper.Invoke(Collection, "Contains", key);
}
public override object CreateElement()
{
return TypeHelper.CreateDefaultInstance(Collection.GetType().GenericTypeArguments[0]);
}
public override void AddElement(object element)
{
ReflectionHelper.Invoke(Collection, "Add", element);
}
public override bool RemoveElement(object element)
{
return (bool)ReflectionHelper.Invoke(Collection, "Remove", element);
}
public override void ClearElements()
{
ReflectionHelper.Invoke(Collection, "Clear");
}
public override HashMapItemBase CreateItem(object collection, object elementObj, string label)
{
return new Item(collection, elementObj, label);
}
public sealed class Item : HashMapItemBase
{
public Item(object collection, object elementObj, string label)
{
var box = new Box()
{
style = {
marginBottom = 3.5f,
marginRight = -2f,
flexDirection = FlexDirection.Row
}
};
var valueType = elementObj == null ? collection.GetType().GenericTypeArguments[0] : elementObj.GetType();
inputField = new GenericField(elementObj, valueType, label);
inputField.style.flexGrow = 1f;
inputField.OnValueChanged += x =>
{
value = x;
OnValueChanged?.Invoke(x);
};
box.Add(inputField);
var closeButton = new Button(() => OnClose?.Invoke())
{
style = {
width = EditorGUIUtility.singleLineHeight,
height = EditorGUIUtility.singleLineHeight,
unityFontStyleAndWeight = FontStyle.Bold,
fontSize = 10f
},
text = "X",
};
box.Add(closeButton);
Add(box);
}
readonly GenericField inputField;
public override void Lock()
{
inputField.SetEnabled(false);
}
object value;
public override object Value => value;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ba0b1c41824514728bc50f6ff3d34315
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,112 +0,0 @@
using System;
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Assertions;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Visual Element that draws the ObjectField of the InlineEditor attribute
/// </summary>
public sealed class InlineEditorObjectField : BindableElement
{
public InlineEditorObjectField(SerializedProperty property, Type type)
{
Assert.IsTrue(property.propertyType == SerializedPropertyType.ObjectReference);
style.minHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
foldout = new Foldout()
{
text = ObjectNames.NicifyVariableName(property.displayName)
};
var toggle = foldout.Q<Toggle>();
var clickable = InternalAPIHelper.GetClickable(toggle);
InternalAPIHelper.SetAcceptClicksIfDisabled(clickable, true);
foldout.BindProperty(property);
inspectorContainer = new VisualElement();
field = new ObjectField()
{
label = ObjectNames.NicifyVariableName(property.displayName),
objectType = type,
allowSceneObjects = !property.GetFieldInfo().HasCustomAttribute<AssetsOnlyAttribute>(),
value = property.objectReferenceValue
};
field.style.position = Position.Absolute;
field.style.width = Length.Percent(100f);
GUIHelper.ScheduleAdjustLabelWidth(field);
OnPropertyChanged(property);
field.RegisterValueChangedCallback(x =>
{
property.objectReferenceValue = x.newValue;
property.serializedObject.ApplyModifiedProperties();
OnPropertyChanged(property);
});
Add(foldout);
Add(field);
}
readonly Foldout foldout;
readonly VisualElement inspectorContainer;
readonly ObjectField field;
bool isNull;
public bool IsObjectNull => isNull;
public string Label
{
get
{
if (isNull) return field.Q<Label>().text;
else return foldout.text;
}
set
{
if (isNull) field.Q<Label>().text = value;
else foldout.text = value;
}
}
void OnPropertyChanged(SerializedProperty property)
{
isNull = property.objectReferenceValue == null;
field.Q<Label>().text = isNull ? ObjectNames.NicifyVariableName(property.displayName) : string.Empty;
field.pickingMode = PickingMode.Ignore;
var objectField = field.Q<ObjectField>();
objectField.pickingMode = PickingMode.Ignore;
var label = objectField.Q<Label>();
label.pickingMode = PickingMode.Ignore;
Build(property);
}
void Build(SerializedProperty property)
{
inspectorContainer.Unbind();
inspectorContainer.Clear();
foldout.Clear();
var toggle = foldout.Q<Toggle>();
isNull = property.objectReferenceValue == null;
toggle.style.display = isNull ? DisplayStyle.None : DisplayStyle.Flex;
if (!isNull)
{
foldout.Add(new VisualElement() { style = { height = EditorGUIUtility.standardVerticalSpacing } });
var so = new SerializedObject(property.objectReferenceValue);
InspectorHelper.BuildElements(so, inspectorContainer, so.targetObject, name => so.FindProperty(name));
inspectorContainer.Bind(so);
foldout.Add(inspectorContainer);
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: c644baa37186c4bbe9c006dee446d9a7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,116 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Visual Element that draws an IList
/// </summary>
public sealed class ListField : VisualElement
{
sealed class Item : VisualElement
{
public int index;
}
const string ItemClassName = "unity-list-view__item";
public ListField(IList target, string label)
{
Assert.IsNotNull(target);
if (target is Array array)
{
this.array = array;
arrayElementType = array.GetType().GetElementType();
var listType = typeof(List<>).MakeGenericType(arrayElementType);
list = (IList)Activator.CreateInstance(listType);
foreach (var item in array) list.Add(item);
}
else
{
list = target;
}
listView = GUIHelper.CreateDefaultListView(label);
listView.makeItem = () => new Item();
listView.bindItem = (element, index) =>
{
((Item)element).index = index;
var value = list[index];
var listType = list.GetType();
var valueType = value != null ? value.GetType() : listType.IsGenericType ? listType.GenericTypeArguments[0] : typeof(object);
var fieldElement = new GenericField(value, valueType, label);
element.Add(fieldElement);
var labelElement = fieldElement.Q<Label>();
if (labelElement != null) labelElement.text = "Element " + index;
fieldElement.OnValueChanged += x =>
{
list[((Item)element).index] = x;
NotifyOnValueChanged();
};
};
listView.unbindItem = (element, index) =>
{
element.Clear();
};
listView.itemsSource = list;
listView.itemIndexChanged += (prevIndex, index) =>
{
var item = listView.Query<VisualElement>(className: ItemClassName).AtIndex(index).Q<Item>();
item.index = index;
NotifyOnValueChanged();
};
listView.itemsAdded += indexes => NotifyOnValueChanged();
listView.itemsRemoved += indexes =>
{
if (arrayElementType == null) listView.schedule.Execute(NotifyOnValueChanged);
else NotifyOnItemsRemoved(indexes);
};
listView.Q<Label>().style.unityFontStyleAndWeight = FontStyle.Bold;
Add(listView);
}
readonly IList list;
readonly ListView listView;
readonly Type arrayElementType;
Array array;
public event Action<object> OnValueChanged;
void NotifyOnValueChanged()
{
if (arrayElementType == null)
{
OnValueChanged?.Invoke(list);
return;
}
if (array.Length != list.Count)
{
array = Array.CreateInstance(arrayElementType, list.Count);
}
list.CopyTo(array, 0);
OnValueChanged?.Invoke(array);
}
void NotifyOnItemsRemoved(IEnumerable<int> indexes)
{
var removedIndexes = new HashSet<int>(indexes);
array = Array.CreateInstance(arrayElementType, list.Count - removedIndexes.Count);
var destinationIndex = 0;
for (var i = 0; i < list.Count; i++)
{
if (removedIndexes.Contains(i)) continue;
array.SetValue(list[i], destinationIndex++);
}
OnValueChanged?.Invoke(array);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: d1b638bf9747241989ead75deeb13093
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,97 +0,0 @@
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public sealed class MethodButton : VisualElement
{
const string ButtonLabelText = "Invoke";
public MethodButton(object target, MethodInfo methodInfo)
{
var parameters = methodInfo.GetParameters();
// Create parameterless button
if (parameters.Length == 0)
{
button = new Button(() => methodInfo.Invoke(target, null))
{
text = methodInfo.Name
};
Add(button);
return;
}
var parameterObjects = new object[parameters.Length];
var box = new HelpBox();
Add(box);
string parameterSignature = string.Join("_", parameters.Select(p => p.ParameterType.Name));
string configKey = $"{target.GetType().FullName}_{methodInfo.Name}_{parameterSignature}_MethodButton";
bool.TryParse(EditorUserSettings.GetConfigValue(configKey), out bool savedFoldoutValue);
foldout = new Foldout()
{
text = methodInfo.Name,
value = savedFoldoutValue,
style = {
flexGrow = 1f
}
};
foldout.RegisterValueChangedCallback(x =>
{
EditorUserSettings.SetConfigValue(configKey, x.newValue.ToString());
});
InternalAPIHelper.SetAcceptClicksIfDisabled(
InternalAPIHelper.GetClickable(foldout.Q<Toggle>()), true
);
button = new Button(() => methodInfo.Invoke(target, parameterObjects))
{
text = ButtonLabelText,
style = {
position = Position.Absolute,
right = 1f,
top = 1.5f,
width = 100f
}
};
box.Add(new VisualElement() { style = { width = 12f } });
box.Add(foldout);
box.Add(button);
for (int i = 0; i < parameters.Length; i++)
{
var index = i;
var parameter = parameters[index];
parameterObjects[index] = parameter.HasDefaultValue
? parameter.DefaultValue
: TypeHelper.CreateDefaultInstance(parameter.ParameterType);
var element = new GenericField(parameterObjects[index], parameter.ParameterType, ObjectNames.NicifyVariableName(parameter.Name));
element.OnValueChanged += x => parameterObjects[index] = x;
element.style.paddingRight = 4f;
foldout.Add(element);
}
}
readonly Foldout foldout;
readonly Button button;
public void SetLableText(string labelText)
{
var foldout = this.Q<Foldout>();
if (foldout != null)
{
foldout.text = labelText;
}
else
{
this.Q<Button>().text = labelText;
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 098870ca8e0fc4d5b80c50ffa39f16f3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,60 +0,0 @@
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Visual Element that draws SerializedProperty of Array or List
/// </summary>
public sealed class PropertyListView : BindableElement
{
public PropertyListView(SerializedProperty property)
{
Assert.IsTrue(property.isArray);
var parentObj = property.GetDeclaredObject();
var events = property.GetAttribute<OnListViewChangedAttribute>(true);
listView = GUIHelper.CreateListViewFromFieldInfo(parentObj, property.GetFieldInfo());
listView.headerTitle = ObjectNames.NicifyVariableName(property.displayName);
listView.bindItem = (element, index) =>
{
var arrayElement = property.GetArrayElementAtIndex(index);
var e = new AlchemyPropertyField(arrayElement, property.GetPropertyType(true), true);
element.Add(e);
element.Bind(arrayElement.serializedObject);
if (events != null)
{
e.TrackPropertyValue(arrayElement, x =>
{
ReflectionHelper.Invoke(parentObj, events.OnItemChanged,
new object[] { index, x.GetValue<object>() });
});
}
};
listView.unbindItem = (element, index) =>
{
element.Clear();
element.Unbind();
};
var label = listView.Q<Label>();
if (label != null) label.style.unityFontStyleAndWeight = FontStyle.Bold;
listView.BindProperty(property);
Add(listView);
}
readonly ListView listView;
public string Label
{
get => listView.headerTitle;
set => listView.headerTitle = value;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: f003dc4ef9602443c8a41555882e68b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,88 +0,0 @@
using System;
using System.Reflection;
using Alchemy.Inspector;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
public sealed class ReflectionField : VisualElement
{
public ReflectionField(object target, MemberInfo memberInfo)
{
Rebuild(target, memberInfo);
}
public void Rebuild(object target, MemberInfo memberInfo)
{
Clear();
if (memberInfo is MethodInfo methodInfo)
{
if (methodInfo.HasCustomAttribute<ButtonAttribute>())
{
var button = new MethodButton(target, methodInfo);
if (methodInfo.TryGetCustomAttribute(out LabelTextAttribute labelText))
{
button.SetLableText(labelText.Text);
}
Add(button);
}
return;
}
object value;
GenericField element;
switch (memberInfo)
{
default: return;
case FieldInfo fieldInfo:
value = fieldInfo.IsStatic ? fieldInfo.GetValue(null) : target == null ? TypeHelper.GetDefaultValue(fieldInfo.FieldType) : fieldInfo.GetValue(target);
var fieldType = target == null ? fieldInfo.FieldType : fieldInfo.GetValue(target)?.GetType() ?? fieldInfo.FieldType;
element = new GenericField(value, fieldType, ObjectNames.NicifyVariableName(memberInfo.Name), true);
element.OnValueChanged += x =>
{
OnBeforeValueChange?.Invoke(target);
fieldInfo.SetValue(target, x);
// Force serialization
if (target is ISerializationCallbackReceiver receiver)
{
receiver.OnBeforeSerialize();
}
OnValueChanged?.Invoke(target);
};
break;
case PropertyInfo propertyInfo:
if (!propertyInfo.HasCustomAttribute<ShowInInspectorAttribute>()) return;
if (!propertyInfo.CanRead) return;
value = propertyInfo.GetMethod.IsStatic ? propertyInfo.GetValue(null) : target == null ? TypeHelper.GetDefaultValue(propertyInfo.PropertyType) : propertyInfo.GetValue(target);
var propertyType = target == null ? propertyInfo.PropertyType : propertyInfo.GetValue(target)?.GetType() ?? propertyInfo.PropertyType;
element = new GenericField(value, propertyType, ObjectNames.NicifyVariableName(memberInfo.Name), true);
element.OnValueChanged += x =>
{
OnBeforeValueChange?.Invoke(target);
if (propertyInfo.CanWrite) propertyInfo.SetValue(target, x);
// Force serialization
if (target is ISerializationCallbackReceiver receiver)
{
receiver.OnBeforeSerialize();
}
OnValueChanged?.Invoke(target);
};
element.SetEnabled(propertyInfo.CanWrite);
break;
}
Add(element);
}
public event Action<object> OnBeforeValueChange;
public event Action<object> OnValueChanged;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e96e973f88c414f90b77487d1a59b89d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,129 +0,0 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UIElements;
namespace Alchemy.Editor.Elements
{
/// <summary>
/// Draw properties marked with SerializeReference attribute
/// </summary>
public sealed class SerializeReferenceField : VisualElement
{
public SerializeReferenceField(SerializedProperty property)
{
Assert.IsTrue(property.propertyType == SerializedPropertyType.ManagedReference);
style.flexDirection = FlexDirection.Row;
style.minHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
foldout = new Foldout()
{
text = ObjectNames.NicifyVariableName(property.displayName)
};
foldout.style.flexGrow = 1f;
foldout.BindProperty(property);
Add(foldout);
buttonContainer = new IMGUIContainer(() =>
{
var position = EditorGUILayout.GetControlRect();
var dropdownRect = position;
dropdownRect.height = EditorGUIUtility.singleLineHeight;
var buttonLabel = EditorIcons.CsScriptIcon;
try
{
if (property != null)
{
buttonLabel.text = (property.managedReferenceValue == null ? "Null" : property.managedReferenceValue.GetType().Name) +
$" ({property.GetManagedReferenceFieldTypeName()})";
}
}
catch (InvalidOperationException)
{
// Ignoring exceptions when disposed (bad solution)
return;
}
if (GUI.Button(dropdownRect, buttonLabel, EditorStyles.objectField))
{
const int MaxTypePopupLineCount = 13;
var baseType = property.GetManagedReferenceFieldType();
SerializeReferenceDropdown dropdown = new(
TypeCache.GetTypesDerivedFrom(baseType).Append(baseType).Where(t =>
(t.IsPublic || t.IsNestedPublic) &&
!t.IsAbstract &&
!t.IsGenericType &&
!typeof(UnityEngine.Object).IsAssignableFrom(t) &&
t.IsSerializable
),
MaxTypePopupLineCount,
new AdvancedDropdownState()
);
dropdown.onItemSelected += item =>
{
property.SetManagedReferenceType(item.type);
property.isExpanded = true;
property.serializedObject.ApplyModifiedProperties();
property.serializedObject.Update();
Rebuild(property);
};
dropdown.Show(position);
}
});
schedule.Execute(() =>
{
var visualTree = panel.visualTree;
visualTree.RegisterCallback<GeometryChangedEvent>(x =>
{
buttonContainer.style.width = GUIHelper.CalculateFieldWidth(buttonContainer, visualTree) -
(buttonContainer.GetFirstAncestorOfType<Foldout>() != null ? 18f : 0f);
});
buttonContainer.style.width = GUIHelper.CalculateFieldWidth(buttonContainer, visualTree) -
(buttonContainer.GetFirstAncestorOfType<Foldout>() != null ? 18f : 0f);
});
buttonContainer.style.position = Position.Absolute;
buttonContainer.style.top = EditorGUIUtility.standardVerticalSpacing * 0.5f;
buttonContainer.style.right = 0f;
Add(buttonContainer);
Rebuild(property);
}
public readonly Foldout foldout;
public readonly IMGUIContainer buttonContainer;
/// <summary>
/// Rebuild child elements
/// </summary>
void Rebuild(SerializedProperty property)
{
foldout.Clear();
if (property.managedReferenceValue == null)
{
var helpbox = new HelpBox("No type assigned.", HelpBoxMessageType.Info);
foldout.Add(helpbox);
}
else
{
InspectorHelper.BuildElements(property.serializedObject, foldout, property.managedReferenceValue, x => property.FindPropertyRelative(x));
}
this.Bind(property.serializedObject);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 03f2015425fd34b8cb49aea8e59f9745
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 7706aa48d1fdb4b70a5b1730f9a590b9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,50 +0,0 @@
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
/// <summary>
/// Base class for adding custom drawing processing to hierarchy items.
/// </summary>
public abstract class HierarchyDrawer
{
#if UNITY_6000_4_OR_NEWER
public abstract void OnGUI(EntityId instanceID, Rect selectionRect);
#else
public abstract void OnGUI(int instanceID, Rect selectionRect);
#endif
protected static Rect GetBackgroundRect(Rect selectionRect)
{
return selectionRect.AddXMax(20f);
}
#if UNITY_6000_4_OR_NEWER
protected static void DrawBackground(EntityId instanceID, Rect selectionRect)
#else
protected static void DrawBackground(int instanceID, Rect selectionRect)
#endif
{
var backgroundRect = GetBackgroundRect(selectionRect);
Color backgroundColor;
var e = Event.current;
var isHover = backgroundRect.Contains(e.mousePosition);
if (Selection.Contains(instanceID))
{
backgroundColor = EditorColors.HighlightBackground;
}
else if (isHover)
{
backgroundColor = EditorColors.HighlightBackgroundInactive;
}
else
{
backgroundColor = EditorColors.WindowBackground;
}
EditorGUI.DrawRect(backgroundRect, backgroundColor);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 99c62ee36c15445da9b11f082910fdfd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,26 +0,0 @@
using System;
using System.Linq;
using UnityEditor;
namespace Alchemy.Editor
{
internal static class HierarchyDrawerInitializer
{
[InitializeOnLoadMethod]
static void Init()
{
var drawers = TypeCache.GetTypesDerivedFrom<HierarchyDrawer>()
.Where(x => !x.IsAbstract)
.Select(x => (HierarchyDrawer)Activator.CreateInstance(x));
foreach (var drawer in drawers)
{
#if UNITY_6000_4_OR_NEWER
EditorApplication.hierarchyWindowItemByEntityIdOnGUI += drawer.OnGUI;
#else
EditorApplication.hierarchyWindowItemOnGUI += drawer.OnGUI;
#endif
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3b5afaf0d349640efa275f491f5caf46
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,42 +0,0 @@
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
public sealed class HierarchyHeaderDrawer : HierarchyDrawer
{
static Color HeaderColor => EditorGUIUtility.isProSkin ? new(0.45f, 0.45f, 0.45f, 0.5f) : new(0.55f, 0.55f, 0.55f, 0.5f);
static GUIStyle labelStyle;
#if UNITY_6000_4_OR_NEWER
public override void OnGUI(EntityId instanceID, Rect selectionRect)
#else
public override void OnGUI(int instanceID, Rect selectionRect)
#endif
{
if (labelStyle == null)
{
labelStyle = new GUIStyle(EditorStyles.boldLabel)
{
alignment = TextAnchor.MiddleCenter,
fontSize = 11,
};
}
#if UNITY_6000_4_OR_NEWER
var gameObject = EditorUtility.EntityIdToObject(instanceID) as GameObject;
#else
var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
#endif
if (gameObject == null) return;
if (!gameObject.TryGetComponent<HierarchyHeader>(out _)) return;
DrawBackground(instanceID, selectionRect);
var headerRect = selectionRect.AddXMax(14f).AddYMax(-1f);
EditorGUI.DrawRect(headerRect, HeaderColor);
EditorGUI.LabelField(headerRect, gameObject.name, labelStyle);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 21aad9026029c4fdfa791adb1c12777b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,29 +0,0 @@
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
internal static class HierarchyObjectCreationMenu
{
[MenuItem("GameObject/Alchemy/Header", false)]
static void CreateHeader(MenuCommand menuCommand)
{
var obj = new GameObject("Header");
obj.AddComponent<HierarchyHeader>();
GameObjectUtility.SetParentAndAlign(obj, menuCommand.context as GameObject);
Undo.RegisterCreatedObjectUndo(obj, "Create " + obj.name);
Selection.activeObject = obj;
}
[MenuItem("GameObject/Alchemy/Separator", false)]
static void CreateSeparator(MenuCommand menuCommand)
{
var obj = new GameObject("Separator");
obj.AddComponent<HierarchySeparator>();
GameObjectUtility.SetParentAndAlign(obj, menuCommand.context as GameObject);
Undo.RegisterCreatedObjectUndo(obj, "Create " + obj.name);
Selection.activeObject = obj;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 0a76950d5487d4ea9a206d592736591b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,26 +0,0 @@
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
[CustomEditor(typeof(HierarchyObject), true)]
[CanEditMultipleObjects]
public sealed class HierarchyObjectEditor : UnityEditor.Editor
{
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
var iterator = serializedObject.GetIterator();
iterator.NextVisible(true);
while (iterator.NextVisible(false))
{
root.Add(new PropertyField(iterator));
}
return root;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ad667e8cf560a44f7a8d1cfd5f79f2df
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,64 +0,0 @@
using System.Linq;
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Alchemy.Editor
{
public sealed class HierarchyObjectProcessor : IProcessSceneWithReport
{
public int callbackOrder => 0;
public void OnProcessScene(Scene scene, BuildReport report)
{
var settings = AlchemySettings.GetOrCreateSettings();
var hierarchyObjects = scene.GetRootGameObjects()
.SelectMany(x => x.GetComponentsInChildren<HierarchyObject>())
.Where(x => x != null)
.OrderByDescending(x => GetDepth(x.transform));
foreach (var obj in hierarchyObjects)
{
if (obj == null) continue;
switch (GetHierarchyObjectMode(obj))
{
case HierarchyObjectMode.None:
break;
case HierarchyObjectMode.RemoveInPlayMode:
obj.transform.DetachChildren();
Object.DestroyImmediate(obj.gameObject);
break;
case HierarchyObjectMode.RemoveInBuild:
if (EditorApplication.isPlaying) break;
obj.transform.DetachChildren();
Object.DestroyImmediate(obj.gameObject);
break;
}
}
}
static HierarchyObjectMode GetHierarchyObjectMode(HierarchyObject obj)
{
return obj.HierarchyObjectMode != HierarchyObject.Mode.UseSettings
? (HierarchyObjectMode)(obj.HierarchyObjectMode - 1)
: AlchemySettings.GetOrCreateSettings().HierarchyObjectMode;
}
static int GetDepth(Transform transform)
{
var depth = 0;
var parent = transform.parent;
while (parent != null)
{
depth++;
parent = parent.parent;
}
return depth;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 41689920aa3aa442ab979a1a81dd7568
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,28 +0,0 @@
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
public class HierarchyRowSeparatorDrawer : HierarchyDrawer
{
#if UNITY_6000_4_OR_NEWER
public override void OnGUI(EntityId instanceID, Rect selectionRect)
#else
public override void OnGUI(int instanceID, Rect selectionRect)
#endif
{
var settings = AlchemySettings.GetOrCreateSettings();
if (!settings.ShowSeparator) return;
var rect = new Rect { y = selectionRect.y, width = selectionRect.width + selectionRect.x, height = 1, x = 0 };
EditorGUI.DrawRect(rect, settings.SeparatorColor);
if (!settings.ShowRowShading) return;
selectionRect.width += selectionRect.x;
selectionRect.x = 0;
selectionRect.height -= 1;
selectionRect.y += 1;
EditorGUI.DrawRect(selectionRect, Mathf.FloorToInt((selectionRect.y - 4) / 16 % 2) == 0 ? settings.EvenRowColor : settings.OddRowColor);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 22beb8e8fe26ffc47853979588eaf7c7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,31 +0,0 @@
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
public sealed class HierarchySeparatorDrawer : HierarchyDrawer
{
static Color SeparatorColor => new(0.5f, 0.5f, 0.5f);
#if UNITY_6000_4_OR_NEWER
public override void OnGUI(EntityId instanceID, Rect selectionRect)
#else
public override void OnGUI(int instanceID, Rect selectionRect)
#endif
{
#if UNITY_6000_4_OR_NEWER
var gameObject = EditorUtility.EntityIdToObject(instanceID) as GameObject;
#else
var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
#endif
if (gameObject == null) return;
if (!gameObject.TryGetComponent<HierarchySeparator>(out _)) return;
DrawBackground(instanceID, selectionRect);
var lineRect = selectionRect.AddY(selectionRect.height * 0.5f).AddXMax(14f).SetHeight(1f);
EditorGUI.DrawRect(lineRect, SeparatorColor);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: cf8a3062aab50494990244011aa1ec06
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,111 +0,0 @@
using System.Linq;
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
public sealed class HierarchyToggleDrawer : HierarchyDrawer
{
#if UNITY_6000_4_OR_NEWER
public override void OnGUI(EntityId instanceID, Rect selectionRect)
#else
public override void OnGUI(int instanceID, Rect selectionRect)
#endif
{
#if UNITY_6000_4_OR_NEWER
var gameObject = EditorUtility.EntityIdToObject(instanceID) as GameObject;
#else
var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
#endif
if (gameObject == null) return;
if (gameObject.TryGetComponent<HierarchyObject>(out _)) return;
var settings = AlchemySettings.GetOrCreateSettings();
if (settings.ShowHierarchyToggles)
{
var rect = selectionRect;
rect.x = rect.xMax - 2.7f;
rect.width = 16f;
if (IsNewPrefabWorkflow() && IsPrefab(gameObject))
rect.x -= 16.7f;
var active = GUI.Toggle(rect, gameObject.activeSelf, string.Empty);
if (active != gameObject.activeSelf)
{
Undo.RecordObject(gameObject, $"{(active ? "Activate" : "Deactivate")} GameObject '{gameObject.name}'");
gameObject.SetActive(active);
EditorUtility.SetDirty(gameObject);
}
}
if (settings.ShowComponentIcons)
{
var rect = selectionRect;
rect.x = rect.xMax - (settings.ShowHierarchyToggles ? 18.7f : 2.7f);
if (IsNewPrefabWorkflow() && IsPrefab(gameObject))
rect.x -= 16.7f;
rect.y += 1f;
rect.width = 14f;
rect.height = 14f;
var components = gameObject
.GetComponents<Component>()
.AsEnumerable()
.Reverse();
var existsScriptIcon = false;
foreach (var component in components)
{
var image = AssetPreview.GetMiniThumbnail(component);
if (image == null) continue;
if (image == EditorIcons.CsScriptIcon.image)
{
if (existsScriptIcon) continue;
existsScriptIcon = true;
}
DrawIcon(ref rect, image, IsEnabled(component) ? Color.white : new(1f, 1f, 1f, 0.5f));
}
}
}
static void DrawIcon(ref Rect rect, Texture image, Color color)
{
var defaultColor = GUI.color;
GUI.color = color;
GUI.DrawTexture(rect, image, ScaleMode.ScaleToFit);
rect.x -= rect.width;
GUI.color = defaultColor;
}
static bool IsEnabled(Component component)
{
var property = component.GetType().GetProperty("enabled", typeof(bool));
return (bool)(property?.GetValue(component, null) ?? true);
}
private static bool IsPrefab(GameObject gameObj)
{
if (gameObj == null)
return false;
var prefabType = PrefabUtility.GetPrefabAssetType(gameObj);
return prefabType != PrefabAssetType.NotAPrefab;
}
private static bool IsNewPrefabWorkflow()
{
#if UNITY_2018_3_OR_NEWER
return true;
#else
return false;
#endif
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 527cfc72d81d34166ab175d08e86e0b5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,148 +0,0 @@
using System.Collections.Generic;
using Alchemy.Hierarchy;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
public class HierarchyTreeMapDrawer : HierarchyDrawer
{
private static readonly Dictionary<string, Texture2D> TextureCached = new();
public static Texture2D TreeMapCurrent
{
get
{
TextureCached.TryGetValue(nameof(TreeMapCurrent), out var tex);
if (tex != null) return tex;
tex = AssetHelper.FindAssetWithPath<Texture2D>("tree_map_current.png", "Editor/Hierarchy/Textures");
TextureCached[nameof(TreeMapCurrent)] = tex;
return tex;
}
}
public static Texture2D TreeMapLast
{
get
{
TextureCached.TryGetValue(nameof(TreeMapLast), out var tex);
if (tex != null) return tex;
tex = AssetHelper.FindAssetWithPath<Texture2D>("tree_map_last.png", "Editor/Hierarchy/Textures");
TextureCached[nameof(TreeMapLast)] = tex;
return tex;
}
}
public static Texture2D TreeMapLevel
{
get
{
TextureCached.TryGetValue(nameof(TreeMapLevel), out var tex);
if (tex != null) return tex;
tex = AssetHelper.FindAssetWithPath<Texture2D>("tree_map_level.png", "Editor/Hierarchy/Textures");
TextureCached[nameof(TreeMapLevel)] = tex;
return tex;
}
}
public static Texture2D TreeMapLine
{
get
{
TextureCached.TryGetValue(nameof(TreeMapLine), out var tex);
if (tex != null) return tex;
tex = AssetHelper.FindAssetWithPath<Texture2D>("tree_map_line.png", "Editor/Hierarchy/Textures");
TextureCached[nameof(TreeMapLine)] = tex;
return tex;
}
}
#if UNITY_6000_4_OR_NEWER
public override void OnGUI(EntityId instanceID, Rect selectionRect)
#else
public override void OnGUI(int instanceID, Rect selectionRect)
#endif
{
#if UNITY_6000_4_OR_NEWER
var gameObject = EditorUtility.EntityIdToObject(instanceID) as GameObject;
#else
var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
#endif
if (gameObject == null) return;
var settings = AlchemySettings.GetOrCreateSettings();
var tempColor = GUI.color;
if (settings.ShowTreeMap)
{
selectionRect.width = 14;
selectionRect.height = 16;
int childCount = gameObject.transform.childCount;
int level = Mathf.RoundToInt(selectionRect.x / 14f);
var t = gameObject.transform;
Transform parent = null;
for (int i = 0, j = level - 1; j >= 0; i++, j--)
{
selectionRect.x = 14 * j;
if (i == 0)
{
if (childCount == 0)
{
GUI.color = settings.TreeMapColor;
GUI.DrawTexture(selectionRect, TreeMapLine);
}
t = gameObject.transform;
}
else if (i == 1)
{
GUI.color = settings.TreeMapColor;
if (parent == null)
{
if (t.GetSiblingIndex() == gameObject.scene.rootCount - 1)
{
GUI.DrawTexture(selectionRect, TreeMapLast);
}
else
{
GUI.DrawTexture(selectionRect, TreeMapCurrent);
}
}
else if (t.GetSiblingIndex() == parent.childCount - 1)
{
GUI.DrawTexture(selectionRect, TreeMapLast);
}
else
{
GUI.DrawTexture(selectionRect, TreeMapCurrent);
}
t = parent;
}
else
{
if (parent == null)
{
if (t.GetSiblingIndex() != gameObject.scene.rootCount - 1) GUI.DrawTexture(selectionRect, TreeMapLevel);
}
else if (t.GetSiblingIndex() != parent.childCount - 1) GUI.DrawTexture(selectionRect, TreeMapLevel);
t = parent;
}
if (t != null) parent = t.parent;
else break;
}
GUI.color = tempColor;
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6ced594b65fdd06438b3a7fb9a468cc6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 6456f2264a0eb3e4ab21dd7eeacaed6a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,166 +0,0 @@
fileFormatVersion: 2
guid: 6fcde88cb33bc664fbdbf06fcb9e61bf
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 2
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 4
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iOS
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

@@ -1,166 +0,0 @@
fileFormatVersion: 2
guid: 0a6f5ce3bc75d6246bf08e03a36ff4a6
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 2
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 4
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iOS
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,166 +0,0 @@
fileFormatVersion: 2
guid: 2506c02ada3af604e85cd968b47c3d62
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 2
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 4
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iOS
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,166 +0,0 @@
fileFormatVersion: 2
guid: dbde2afdf4cde684da439f40428c19c4
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 2
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 4
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iOS
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: 50
textureCompression: 1
compressionQuality: 100
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 32
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 9243210c5444145978ade99e7a7af0c1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,26 +0,0 @@
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
internal static class AssetHelper
{
public static T FindAssetWithPath<T>(string nameAsset, string relativePath, bool outsideScope = false) where T : Object
{
string path = outsideScope ? $"{relativePath}/{nameAsset}" : AssetInPackagePath(relativePath, nameAsset);
var t = AssetDatabase.LoadAssetAtPath(path, typeof(T));
if (t == null) Debug.LogError($"Couldn't load the {nameof(T)} at path :{path}");
return t as T;
}
private static string AssetInPackagePath(string relativePath, string nameAsset) { return GetPathInCurrentEnvironent($"{relativePath}/{nameAsset}"); }
private static string GetPathInCurrentEnvironent(string fullRelativePath)
{
var upmPath = $"Packages/com.annulusgames.alchemy/{fullRelativePath}";
var normalPath = $"Assets/Alchemy/{fullRelativePath}";
return !File.Exists(Path.GetFullPath(upmPath)) ? normalPath : upmPath;
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: dd030e11e64f4eedbd42c8bc0afd5ae1
timeCreated: 1714886762
@@ -1,71 +0,0 @@
using System;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
// Rererence: https://www.foundations.unity.com/fundamentals/color-palette
internal static class EditorColors
{
static Color GetColor(string htmlColor)
{
if (!ColorUtility.TryParseHtmlString(htmlColor, out var color)) throw new ArgumentException();
return color;
}
public static Color DefaultBackground
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#282828");
else return GetColor("#A5A5A5");
}
}
public static Color HighlightBackgroundInactive
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#4D4D4D");
else return GetColor("#AEAEAE");
}
}
public static Color HighlightBackground
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#2C5D87");
else return GetColor("#3A72B0");
}
}
public static Color WindowBackground
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#383838");
else return GetColor("#C8C8C8");
}
}
public static Color InspectorTitlebarBorder
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#1A1A1A");
else return GetColor("#7F7F7F");
}
}
public static Color DefaultText
{
get
{
if (EditorGUIUtility.isProSkin) return GetColor("#D2D2D2");
else return GetColor("#090909");
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e417a3e095b0d43a1b3d886d05d2b4c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,10 +0,0 @@
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
internal static class EditorIcons
{
public static readonly GUIContent CsScriptIcon = EditorGUIUtility.IconContent("cs Script Icon");
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b5d3e43f293fb4a7ebcba1e3b2b91f2b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,195 +0,0 @@
using System;
using System.Reflection;
using Alchemy.Inspector;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
internal static class GUIHelper
{
public static Color LineColor => EditorGUIUtility.isProSkin ? new(0.4f, 0.4f, 0.4f) : new(0.6f, 0.6f, 0.6f);
public static Color SubtitleColor => new(0.5f, 0.5f, 0.5f);
public static Color TextColor => EditorGUIUtility.isProSkin ? new(0.725f, 0.725f, 0.725f) : new(0.141f, 0.141f, 0.141f);
public static float CalculateFieldWidth(VisualElement element, VisualElement root)
{
var labelWidth = CalculateLabelWidth(element, root);
return root.resolvedStyle.width - labelWidth - 27f;
}
public static float CalculateLabelWidth(VisualElement element, VisualElement root)
{
// This code is a partial modification of the Label width calculation method actually used inside PropertyField.
var num = root.resolvedStyle.paddingLeft;
var num2 = 37f;
var num3 = 123f;
var num4 = element.GetFirstAncestorOfType<Foldout>() == null ? 0f : 15f;
var width = root.resolvedStyle.width;
var a = width * 0.45f - num2 - num - num4;
var b = Mathf.Max(num3 - num - num4, 0f);
return Mathf.Max(a, b) + 12f;
}
public static ListView CreateDefaultListView(string label)
{
return new ListView()
{
reorderable = true,
reorderMode = ListViewReorderMode.Animated,
showBorder = true,
showFoldoutHeader = true,
headerTitle = label,
showAddRemoveFooter = true,
fixedItemHeight = 20f,
virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight,
showAlternatingRowBackgrounds = AlternatingRowBackground.None,
};
}
public static ListView CreateListViewFromFieldInfo(object target, FieldInfo fieldInfo)
{
var settings = fieldInfo.GetCustomAttribute<ListViewSettingsAttribute>();
var listView = new ListView
{
reorderable = settings == null ? true : settings.Reorderable,
reorderMode = settings == null ? ListViewReorderMode.Animated : settings.ReorderMode,
showBorder = settings == null ? true : settings.ShowBorder,
showFoldoutHeader = settings == null ? true : settings.ShowFoldoutHeader,
showBoundCollectionSize = settings == null ? true : (settings.ShowFoldoutHeader && settings.ShowBoundCollectionSize),
selectionType = settings == null ? SelectionType.Multiple : settings.SelectionType,
showAddRemoveFooter = settings == null ? true : settings.ShowAddRemoveFooter,
fixedItemHeight = 20f,
virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight,
showAlternatingRowBackgrounds = settings == null ? AlternatingRowBackground.None : settings.ShowAlternatingRowBackgrounds,
};
var events = fieldInfo.GetCustomAttribute<OnListViewChangedAttribute>();
if (events != null)
{
listView.itemsAdded += indices =>
{
if (events.OnItemsAdded == null) return;
ReflectionHelper.Invoke(target, events.OnItemsAdded, new object[] { indices });
};
listView.itemsRemoved += indices =>
{
if (events.OnItemsRemoved == null) return;
ReflectionHelper.Invoke(target, events.OnItemsRemoved, new object[] { indices });
};
#if UNITY_2022_1_OR_NEWER
listView.itemsChosen += items =>
{
if (events.OnItemsChosen == null) return;
ReflectionHelper.Invoke(target, events.OnItemsChosen, new object[] { items });
};
#else
listView.onItemsChosen += items =>
{
if (events.OnItemsChosen == null) return;
ReflectionHelper.Invoke(target, events.OnItemsChosen, new object[] { items });
};
#endif
listView.itemIndexChanged += (before, after) =>
{
if (events.OnItemIndexChanged == null) return;
ReflectionHelper.Invoke(target, events.OnItemIndexChanged, new object[] { before, after });
};
#if UNITY_2022_1_OR_NEWER
listView.selectionChanged += items =>
{
if (events.OnSelectionChanged == null) return;
ReflectionHelper.Invoke(target, events.OnSelectionChanged, new object[] { items });
};
listView.selectedIndicesChanged += indices =>
{
if (events.OnSelectedIndicesChanged == null) return;
ReflectionHelper.Invoke(target, events.OnSelectedIndicesChanged, new object[] { indices });
};
#else
listView.onSelectionChange += items =>
{
if (events.OnSelectionChanged == null) return;
ReflectionHelper.Invoke(target, events.OnSelectionChanged, new object[] { items });
};
listView.onSelectedIndicesChange += indices =>
{
if (events.OnSelectedIndicesChanged== null) return;
ReflectionHelper.Invoke(target, events.OnSelectedIndicesChanged, new object[] { indices });
};
#endif
listView.itemsSourceChanged += () =>
{
if (events.OnItemsSourceChanged == null) return;
ReflectionHelper.Invoke(target, events.OnItemsSourceChanged, null);
};
}
return listView;
}
public static PropertyField CreateObjectPropertyField(SerializedProperty property, Type type)
{
Assert.IsTrue(property.propertyType == SerializedPropertyType.ObjectReference);
var fieldInfo = property.GetFieldInfo();
var isAssetsOnly = fieldInfo.HasCustomAttribute<AssetsOnlyAttribute>();
var propertyField = new PropertyField(property);
propertyField.RegisterValueChangeCallback(x =>
{
var objectField = propertyField.Q<ObjectField>();
if (objectField == null) return;
objectField.objectType = type;
objectField.allowSceneObjects = !isAssetsOnly;
});
return propertyField;
}
public static void ScheduleAdjustLabelWidth(VisualElement element)
{
void Adjust(VisualElement visualElement)
{
var label = element.Q<Label>();
if (label == null) return;
label.style.minWidth = 0f;
label.style.width = CalculateLabelWidth(element, visualElement);
}
// Adjust label width
element.schedule.Execute(() =>
{
var visualTree = element.panel.visualTree;
visualTree.RegisterCallback<GeometryChangedEvent>(x => Adjust(visualTree));
Adjust(visualTree);
});
}
public static IMGUIContainer CreateLine(Color color, float height)
{
return new IMGUIContainer(() =>
{
var rect = EditorGUILayout.GetControlRect(false, height);
rect.xMin += 3f;
rect.y += rect.height * 0.5f;
rect.height = 1f;
EditorGUI.DrawRect(rect, color);
});
}
public static void SetMinAndCurrentWidth(VisualElement visualElement, float value)
{
visualElement.style.minWidth = value;
visualElement.style.width = value;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b23551d43228a43c9a9207cf8f150834
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,312 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Alchemy.Inspector;
using Alchemy.Editor.Elements;
#if ALCHEMY_SUPPORT_SERIALIZATION
using Alchemy.Serialization;
#endif
namespace Alchemy.Editor
{
internal static class InspectorHelper
{
public sealed class GroupNode
{
public GroupNode(string name, AlchemyGroupDrawer drawer)
{
this.name = name;
this.drawer = drawer;
}
readonly string name;
readonly AlchemyGroupDrawer drawer;
readonly List<MemberInfo> members = new();
readonly List<GroupNode> children = new();
public string Name => name;
public IEnumerable<MemberInfo> Members => members;
public AlchemyGroupDrawer Drawer => drawer;
public VisualElement VisualElement { get; set; }
public GroupNode Parent { get; private set; }
public GroupNode Find(Func<GroupNode, bool> predicate)
{
return children.FirstOrDefault(predicate);
}
public void Add(GroupNode node)
{
children.Add(node);
node.Parent = this;
}
public void AddMember(MemberInfo memberInfo)
{
members.Add(memberInfo);
}
public IEnumerable<GroupNode> DescendantsAndSelf()
{
yield return this;
foreach (var item in Descendants(children)) yield return item;
}
static IEnumerable<GroupNode> Descendants(IEnumerable<GroupNode> source)
{
foreach (var item in source)
{
yield return item;
var e = Descendants(item.children).GetEnumerator();
while (e.MoveNext())
{
yield return e.Current;
}
}
}
}
public static void BuildElements(SerializedObject serializedObject, VisualElement rootElement, object target, Func<string, SerializedProperty> findPropertyFunc)
{
if (target == null) return;
// Build node
var rootNode = BuildInspectorNode(target.GetType());
// Add elements
foreach (var node in rootNode.DescendantsAndSelf())
{
// Get or create group element
if (node.Parent == null)
{
node.VisualElement = rootElement;
}
else if (node.Drawer == null)
{
node.VisualElement = node.Parent.VisualElement;
}
else
{
node.VisualElement = node.Drawer.CreateRootElement(node.Name);
node.Parent.VisualElement.Add(node.VisualElement);
}
// Add member elements
foreach (var member in node.Members.OrderByAttributeThenByMemberType())
{
// Exclude if member has HideInInspector attribute
// but not "m_SerializedDataModeController" on EditorWindow
// (Unity added HideInInspector here in 2022.3.23f1)
if (member.HasCustomAttribute<HideInInspector>() && member.Name != "m_SerializedDataModeController")
continue;
// Add default PropertyField if member has DisableAlchemyEditorAttribute
if (member.GetCustomAttribute<DisableAlchemyEditorAttribute>() != null)
{
var p = findPropertyFunc(member.Name);
if (p != null)
{
var propertyField = new PropertyField(p);
propertyField.style.width = Length.Percent(100f);
node.VisualElement.Add(propertyField);
}
continue;
}
VisualElement element = null;
var property = findPropertyFunc(member.Name);
var isManagedReferenceProperty = property?.propertyType == SerializedPropertyType.ManagedReference;
// Add default PropertyField if the property has a custom PropertyDrawer
if ((member is FieldInfo fieldInfo && InternalAPIHelper.GetDrawerTypeForType(fieldInfo.FieldType, isManagedReferenceProperty) != null) ||
(member is PropertyInfo propertyInfo && InternalAPIHelper.GetDrawerTypeForType(propertyInfo.PropertyType, isManagedReferenceProperty) != null))
{
if (property != null)
{
element = new PropertyField(property);
}
}
else
{
element = CreateMemberElement(serializedObject, target, member, findPropertyFunc);
}
if (element == null) continue;
element.style.width = Length.Percent(100f);
var e = node.Drawer?.GetGroupElement(
member.GetCustomAttributes<PropertyGroupAttribute>()
.OrderByDescending(x => x.GroupPath.Split('/').Length)
.FirstOrDefault()
);
if (e == null) node.VisualElement.Add(element);
else e.Add(element);
AlchemyAttributeDrawer.ExecutePropertyDrawers(serializedObject, property, target, member, element);
}
}
}
internal static GroupNode BuildInspectorNode(Type targetType)
{
var rootNode = new GroupNode("Inspector-Group-Root", null);
// Get all members
var members = ReflectionHelper.GetMembers(targetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, true)
.Where(x => x is MethodInfo or FieldInfo or PropertyInfo);
// Build member nodes
foreach (var member in members)
{
var groupAttributes = member.GetCustomAttributes<PropertyGroupAttribute>(true);
if (groupAttributes.Count() == 0)
{
rootNode.AddMember(member);
continue;
}
var parentNode = rootNode;
foreach (var (groupAttribute, hierarchy) in groupAttributes
.Select(x => (x, x.GroupPath.Split('/')))
.OrderBy(x => x.Item2.Length))
{
parentNode = rootNode;
foreach (var groupName in hierarchy)
{
var next = parentNode.Find(x => x.Name == groupName);
if (next == null)
{
var drawer = AlchemyEditorUtility.CreateGroupDrawer(groupAttribute, targetType);
next = new GroupNode(groupName, drawer);
parentNode.Add(next);
}
parentNode = next;
}
}
parentNode.AddMember(member);
}
return rootNode;
}
public static VisualElement CreateMemberElement(SerializedObject serializedObject, object target, MemberInfo memberInfo, Func<string, SerializedProperty> findPropertyFunc)
{
switch (memberInfo)
{
case MethodInfo methodInfo:
if (methodInfo.HasCustomAttribute<ButtonAttribute>())
{
return new MethodButton(target, methodInfo);
}
break;
case FieldInfo:
case PropertyInfo:
var isSerializedMember = false;
if (memberInfo is FieldInfo f) isSerializedMember = f.IsPublic | f.HasCustomAttribute<SerializeField>() | f.HasCustomAttribute<SerializeReference>();
else if (memberInfo is PropertyInfo p) isSerializedMember = p.HasCustomAttribute<SerializeField>();
if (isSerializedMember)
{
var property = findPropertyFunc?.Invoke(memberInfo.Name);
// Create property field
if (property != null)
{
if (memberInfo is FieldInfo fieldInfo)
{
return new AlchemyPropertyField(property, fieldInfo.FieldType);
}
else
{
return new AlchemyPropertyField(property, ((PropertyInfo)memberInfo).PropertyType);
}
}
}
#if ALCHEMY_SUPPORT_SERIALIZATION
if (serializedObject.targetObject != null &&
memberInfo.DeclaringType.HasCustomAttribute<AlchemySerializeAttribute>() &&
memberInfo.HasCustomAttribute<AlchemySerializeFieldAttribute>())
{
var element = default(VisualElement);
if (memberInfo is FieldInfo fieldInfo)
{
var declaredType = fieldInfo.DeclaringType;
if (declaredType.IsConstructedGenericType)
{
declaredType = declaredType.GetGenericTypeDefinition();
}
var dataName = "__alchemySerializationData_" + declaredType.FullName.Replace("`", "").Replace(".", "_");
SerializedProperty GetProperty() => findPropertyFunc?.Invoke(dataName)
.FindPropertyRelative(memberInfo.Name);
var p = GetProperty();
if (p != null)
{
var field = new ReflectionField(target, fieldInfo);
var foldout = field.Q<Foldout>();
foldout?.BindProperty(p);
field.TrackPropertyValue(p, p =>
{
field.Rebuild(target, memberInfo);
var foldout = field.Q<Foldout>();
foldout?.BindProperty(p);
});
var undoName = "Modified:" + p.displayName;
field.OnBeforeValueChange += x =>
{
Undo.RegisterCompleteObjectUndo(GetProperty().serializedObject.targetObject, undoName);
};
element = field;
}
}
// TODO: Supports editing of multiple objects
if (element != null && serializedObject.targetObjects.Length > 1)
{
element.SetEnabled(false);
}
return element;
}
#endif
// Create element if member has ShowInInspector attribute
if (memberInfo.HasCustomAttribute<ShowInInspectorAttribute>())
{
return new ReflectionField(target, memberInfo);
}
break;
}
return null;
}
internal static IOrderedEnumerable<MemberInfo> OrderByAttributeThenByMemberType(this IEnumerable<MemberInfo> members)
{
return members
.OrderBy(x =>
{
var orderAttribute = x.GetCustomAttribute<OrderAttribute>();
if (orderAttribute == null) return 0;
return orderAttribute.Order;
})
.ThenBy(x =>
{
if (x is MethodInfo) return 1;
return 0;
});
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 664a7f04961bd4d6fb7fa0bcaf290687
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,77 +0,0 @@
using System;
using System.Reflection;
using UnityEngine.UIElements;
namespace Alchemy.Editor
{
using Editor = UnityEditor.Editor;
/// <summary>
/// Call the Unity internal API using reflection. This may not work depending on your Unity version.
/// </summary>
internal static class InternalAPIHelper
{
static readonly Assembly EditorAssembly = Assembly.GetAssembly(typeof(Editor));
// ScriptAttributeUtility
// https://github.com/Unity-Technologies/UnityCsReference/blob/724ff727438a68d1bc05b342c693c1d481063fd3/Editor/Mono/Inspector/Core/ScriptAttributeGUI/ScriptAttributeUtility.cs
const string Name_ScriptAttributeUtility = "UnityEditor.ScriptAttributeUtility";
public static Type GetDrawerTypeForType(Type classType, bool isManagedReferenceProperty)
{
var instance = EditorAssembly.CreateInstance(Name_ScriptAttributeUtility);
var utilityType = instance.GetType();
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;
var methodInfo = utilityType.GetMethod(nameof(GetDrawerTypeForType), bindingFlags);
#if UNITY_2023_3_OR_NEWER
return (Type)methodInfo.Invoke(instance, new object[] { classType, null, isManagedReferenceProperty });
#elif UNITY_2023_2_OR_NEWER
// Unity 2023.2.15f1 added a new parameter to the method
var version = UnityEditorInternal.InternalEditorUtility.GetUnityVersion();
if (version.Build >= 15)
{
return (Type)methodInfo.Invoke(instance, new object[] { classType, isManagedReferenceProperty });
}
else
{
return (Type)methodInfo.Invoke(instance, new object[] { classType });
}
#elif UNITY_2022_3_OR_NEWER
// Unity 2022.3.23f1 added a new parameter to the method
var version = UnityEditorInternal.InternalEditorUtility.GetUnityVersion();
if (version.Build >= 23)
{
return (Type)methodInfo?.Invoke(instance, new object[] { classType, isManagedReferenceProperty });
}
return (Type)methodInfo?.Invoke(instance, new object[] { classType });
#else
_ = isManagedReferenceProperty; // discard
return (Type)methodInfo.Invoke(instance, new object[] { classType });
#endif
}
const string Name_M_Clickable = "m_Clickable";
// BaseBoolField
// https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Core/Controls/BaseBoolField.cs#L12
public static Clickable GetClickable(BaseBoolField boolField)
{
var clickable = ReflectionHelper.GetField(typeof(Toggle), Name_M_Clickable).GetValue(boolField);
return (Clickable)clickable;
}
// Clickable
// https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Core/Clickable.cs#L12
const string Name_AcceptClicksIfDisabled = "acceptClicksIfDisabled";
public static void SetAcceptClicksIfDisabled(Clickable clickable, bool value)
{
ReflectionHelper.GetProperty(typeof(Clickable), Name_AcceptClicksIfDisabled).SetValue(clickable, value);
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: bd2e9148da43349219f92b909651fbdc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,19 +0,0 @@
using System;
using System.Reflection;
namespace Alchemy.Editor
{
internal static class MemberInfoExtensions
{
public static bool HasCustomAttribute<T>(this MemberInfo memberInfo) where T : Attribute
{
return memberInfo.GetCustomAttribute<T>() != null;
}
public static bool TryGetCustomAttribute<T>(this MemberInfo memberInfo, out T result) where T : Attribute
{
result = memberInfo.GetCustomAttribute<T>();
return result != null;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4786119bc20d840f7b77860f7b16e18c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,78 +0,0 @@
using UnityEngine;
namespace Alchemy.Editor
{
internal static class RectHelper
{
public static Rect Expand(this Rect rect, float value)
{
rect.xMin -= value;
rect.xMax += value;
rect.yMin -= value;
rect.yMax += value;
return rect;
}
public static Rect ExpandX(this Rect rect, float value)
{
rect.xMin -= value;
rect.xMax += value;
return rect;
}
public static Rect ExpandY(this Rect rect, float value)
{
rect.yMin -= value;
rect.yMax += value;
return rect;
}
public static Rect AddX(this Rect rect, float value)
{
rect.x += value;
return rect;
}
public static Rect AddY(this Rect rect, float value)
{
rect.y += value;
return rect;
}
public static Rect AddXMin(this Rect rect, float value)
{
rect.xMin += value;
return rect;
}
public static Rect AddXMax(this Rect rect, float value)
{
rect.xMax += value;
return rect;
}
public static Rect AddYMin(this Rect rect, float value)
{
rect.yMin += value;
return rect;
}
public static Rect AddYMax(this Rect rect, float value)
{
rect.yMax += value;
return rect;
}
public static Rect SetWidth(this Rect rect, float value)
{
rect.width = value;
return rect;
}
public static Rect SetHeight(this Rect rect, float value)
{
rect.height = value;
return rect;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4ebc9adffd3924cb68c38dd5d6789d24
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,314 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Alchemy.Editor
{
internal static class ReflectionHelper
{
static readonly Dictionary<(Type, string, BindingFlags, bool), FieldInfo> cacheFieldInfo = new();
static readonly Dictionary<(Type, string, BindingFlags, bool), MethodInfo> cacheMethodInfo = new();
static readonly Dictionary<(Type, string, BindingFlags, bool), PropertyInfo> cachePropertyInfo = new();
static readonly Dictionary<(Type, BindingFlags, bool), MemberInfo[]> cacheAllMembers = new();
static readonly Dictionary<(Type, string), Func<object, object>> cacheGetFieldValue = new();
static readonly Dictionary<(Type, string), Func<object, object>> cacheGetPropertyValue = new();
static readonly Dictionary<(Type, string), Func<object, object>> cacheGetMethodValue = new();
public static Func<object, object> CreateGetter(FieldInfo fieldInfo)
{
if (fieldInfo == null) return null;
if (fieldInfo.IsStatic)
{
var body = Expression.Convert(Expression.MakeMemberAccess(null, fieldInfo), typeof(object));
var lambda = Expression.Lambda<Func<object>>(body).Compile();
return _ => lambda();
}
if (fieldInfo.DeclaringType != null)
{
var objParam = Expression.Parameter(typeof(object), "obj");
var tParam = Expression.Convert(objParam, fieldInfo.DeclaringType);
var body = Expression.Convert(Expression.MakeMemberAccess(tParam, fieldInfo), typeof(object));
return Expression.Lambda<Func<object, object>>(body, objParam).Compile();
}
return null;
}
public static Func<object, object> CreateGetter(PropertyInfo propertyInfo)
{
if (propertyInfo == null) return null;
if (propertyInfo.GetGetMethod(true).IsStatic)
{
var body = Expression.Convert(Expression.MakeMemberAccess(null, propertyInfo), typeof(object));
var lambda = Expression.Lambda<Func<object>>(body).Compile();
return _ => lambda();
}
if (propertyInfo.DeclaringType != null)
{
var objParam = Expression.Parameter(typeof(object), "obj");
var tParam = Expression.Convert(objParam, propertyInfo.DeclaringType);
var body = Expression.Convert(Expression.MakeMemberAccess(tParam, propertyInfo), typeof(object));
return Expression.Lambda<Func<object, object>>(body, objParam).Compile();
}
return null;
}
public static Func<object, object> CreateGetter(MethodInfo methodInfo)
{
if (methodInfo == null) return null;
if (methodInfo.IsStatic)
{
var body = Expression.Convert(Expression.Call(null, methodInfo), typeof(object));
var lambda = Expression.Lambda<Func<object>>(body).Compile();
return _ => lambda();
}
if (methodInfo.DeclaringType != null)
{
var objParam = Expression.Parameter(typeof(object), "obj");
var tParam = Expression.Convert(objParam, methodInfo.DeclaringType);
var body = Expression.Convert(Expression.Call(tParam, methodInfo), typeof(object));
return Expression.Lambda<Func<object, object>>(body, objParam).Compile();
}
return null;
}
public static object GetFieldValue(object target, Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
if (!cacheGetFieldValue.TryGetValue((type, name), out var value))
{
var info = type.GetField(name, bindingAttr);
value = CreateGetter(info);
cacheGetFieldValue.Add((type, name), value);
}
return value?.Invoke(target);
}
public static object GetPropertyValue(object target, Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
if (!cacheGetPropertyValue.TryGetValue((type, name), out var value))
{
var info = type.GetProperty(name, bindingAttr);
value = CreateGetter(info);
cacheGetPropertyValue.Add((type, name), value);
}
return value?.Invoke(target);
}
public static object GetMethodValue(object target, Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
if (!cacheGetMethodValue.TryGetValue((type, name), out var value))
{
var info = type.GetMethod(name, bindingAttr);
value = CreateGetter(info);
cacheGetMethodValue.Add((type, name), value);
}
return value?.Invoke(target);
}
public static FieldInfo GetField(Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, bool includingBaseNonPublic = false)
{
if (!cacheFieldInfo.TryGetValue((type, name, bindingAttr, includingBaseNonPublic), out var info))
{
if (includingBaseNonPublic)
{
info = GetAllFieldsIncludingBaseNonPublic(type, bindingAttr).FirstOrDefault(x => x.Name == name);
}
else
{
info = type.GetField(name, bindingAttr);
}
cacheFieldInfo.Add((type, name, bindingAttr, includingBaseNonPublic), info);
}
return info;
}
static IEnumerable<Type> EnumerateTypeHierarchy(Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
public static IEnumerable<FieldInfo> GetAllFieldsIncludingBaseNonPublic(Type type, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
return EnumerateTypeHierarchy(type).Reverse().SelectMany(t => t.GetFields(bindingAttr | BindingFlags.DeclaredOnly));
}
public static PropertyInfo GetProperty(Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, bool includingBaseNonPublic = false)
{
if (!cachePropertyInfo.TryGetValue((type, name, bindingAttr, includingBaseNonPublic), out var info))
{
if (includingBaseNonPublic)
{
info = GetAllPropertiesIncludingBaseNonPublic(type, bindingAttr).FirstOrDefault(x => x.Name == name);
}
else
{
info = type.GetProperty(name, bindingAttr);
}
cachePropertyInfo.Add((type, name, bindingAttr, includingBaseNonPublic), info);
}
return info;
}
public static IEnumerable<PropertyInfo> GetAllPropertiesIncludingBaseNonPublic(Type type, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
return EnumerateTypeHierarchy(type).Reverse().SelectMany(t => t.GetProperties(bindingAttr | BindingFlags.DeclaredOnly));
}
public static MethodInfo GetMethod(Type type, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, bool includingBaseNonPublic = false)
{
if (!cacheMethodInfo.TryGetValue((type, name, bindingAttr, includingBaseNonPublic), out var info))
{
if (includingBaseNonPublic)
{
info = GetAllMethodsIncludingBaseNonPublic(type, bindingAttr).FirstOrDefault(x => x.Name == name);
}
else
{
info = type.GetMethods(bindingAttr).Where(x => x.Name == name).FirstOrDefault();
}
cacheMethodInfo.Add((type, name, bindingAttr, includingBaseNonPublic), info);
}
return info;
}
public static IEnumerable<MethodInfo> GetAllMethodsIncludingBaseNonPublic(Type type, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
return EnumerateTypeHierarchy(type).Reverse().SelectMany(t => t.GetMethods(bindingAttr | BindingFlags.DeclaredOnly));
}
public static object GetValue(object target, string name, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, bool allowProperty = true, bool allowMethod = true)
{
if (target == null) return null;
Type type = target.GetType();
object result;
while (type != null)
{
result = GetFieldValue(target, type, name, bindingAttr);
if (result != null) return result;
if (allowProperty)
{
result = GetPropertyValue(target, type, name, bindingAttr);
if (result != null) return result;
}
if (allowMethod)
{
result = GetMethodValue(target, type, name, bindingAttr);
if (result != null) return result;
}
type = type.BaseType;
}
return null;
}
public static object GetValue(object target, string name, int index)
{
if (GetValue(target, name, allowMethod: false) is not IEnumerable enumerable) return null;
IEnumerator enumerator = enumerable.GetEnumerator();
for (int i = 0; i <= index; i++)
{
if (!enumerator.MoveNext()) return null;
}
return enumerator.Current;
}
public static bool GetValueBool(object target, string name)
{
if (GetValue(target, name) is bool cond)
{
return cond;
}
return false;
}
public static MemberInfo[] GetMembers(Type type, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, bool includingBaseNonPublic = false)
{
if (cacheAllMembers.TryGetValue((type, bindingAttr, includingBaseNonPublic), out var memberInfoArray))
{
return memberInfoArray;
}
else
{
if (includingBaseNonPublic)
{
memberInfoArray = GetMembersIncludingBaseNonPublic(type, bindingAttr).ToArray();
}
else
{
memberInfoArray = type.GetMembers(bindingAttr);
}
cacheAllMembers.Add((type, bindingAttr, includingBaseNonPublic), memberInfoArray);
return memberInfoArray;
}
}
public static IEnumerable<MemberInfo> GetMembersIncludingBaseNonPublic(Type type, BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
{
return EnumerateTypeHierarchy(type).Reverse().SelectMany(t => t.GetMembers(bindingAttr | BindingFlags.DeclaredOnly));
}
public static object Invoke(object target, string name, params object[] parameters)
{
if (target == null) return false;
Type type = target.GetType();
BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
while (type != null)
{
var m = GetMethod(type, name, bindingAttr);
if (m != null) return m.Invoke(m.IsStatic ? null : target, parameters);
type = type.BaseType;
}
return false;
}
public static bool TryInvoke(object target, string name, object[] parameters, out object result)
{
if (target == null)
{
result = default;
return false;
}
Type type = target.GetType();
BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
while (type != null)
{
var m = GetMethod(type, name, bindingAttr);
if (m != null)
{
result = m.Invoke(m.IsStatic ? null : target, parameters);
return true;
}
type = type.BaseType;
}
result = default;
return false;
}
public static object GetCollectionValue(object target, int index)
{
var type = target.GetType();
if (type.IsArray) return ((Array)target).GetValue(index);
else if (target is IList list) return list[index];
return null;
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 7ddc52eddda264fba8fea9844f3c0f61
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,157 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace Alchemy.Editor
{
internal sealed class SerializeReferenceDropdownItem : AdvancedDropdownItem
{
public readonly Type type;
public SerializeReferenceDropdownItem(Type type, string name) : base(name)
{
this.type = type;
if (type != null) icon = (Texture2D)EditorIcons.CsScriptIcon.image;
}
}
internal sealed class SerializeReferenceDropdown : AdvancedDropdown
{
private static readonly float headerHeight = EditorGUIUtility.singleLineHeight * 2f;
private static readonly int maxNamespaceNestCount = 16;
private static readonly string nullDisplayName = "(Null)";
private Type[] types;
public event Action<SerializeReferenceDropdownItem> onItemSelected;
public static void AddTo(AdvancedDropdownItem root, IEnumerable<Type> types)
{
var itemCount = 0;
var nullItem = new SerializeReferenceDropdownItem(null, nullDisplayName)
{
id = itemCount++
};
root.AddChild(nullItem);
var typeArray = types.OrderBy(x => x.FullName);
var isSingleNamespace = true;
var namespaces = new string[maxNamespaceNestCount];
foreach (Type type in typeArray)
{
var splittedTypePath = GetSplittedTypePath(type);
if (splittedTypePath.Length <= 1) continue;
for (int i = 0; (splittedTypePath.Length - 1) > i; i++)
{
var ns = namespaces[i];
if (ns == null)
{
namespaces[i] = splittedTypePath[i];
}
else if (ns != splittedTypePath[i])
{
isSingleNamespace = false;
break;
}
}
if (!isSingleNamespace)
{
break;
}
}
foreach (var type in typeArray)
{
var splittedTypePath = GetSplittedTypePath(type);
if (splittedTypePath.Length == 0) continue;
var parent = root;
if (!isSingleNamespace)
{
for (int i = 0; (splittedTypePath.Length - 1) > i; i++)
{
var foundItem = GetItem(parent, splittedTypePath[i]);
if (foundItem != null)
{
parent = foundItem;
}
else
{
var newItem = new AdvancedDropdownItem(splittedTypePath[i])
{
id = itemCount++,
};
parent.AddChild(newItem);
parent = newItem;
}
}
}
var item = new SerializeReferenceDropdownItem(type, ObjectNames.NicifyVariableName(splittedTypePath[^1]))
{
id = itemCount++
};
parent.AddChild(item);
}
}
static AdvancedDropdownItem GetItem(AdvancedDropdownItem parent, string name)
{
#if UNITY_6000_5_OR_NEWER
foreach (AdvancedDropdownItem item in parent.childList)
#else
foreach (AdvancedDropdownItem item in parent.children)
#endif
{
if (item.name == name) return item;
}
return null;
}
public SerializeReferenceDropdown(IEnumerable<Type> types, int maxLineCount, AdvancedDropdownState state) : base(state)
{
SetTypes(types);
minimumSize = new(minimumSize.x, EditorGUIUtility.singleLineHeight * maxLineCount + headerHeight);
}
public void SetTypes(IEnumerable<Type> types)
{
this.types = types.ToArray();
}
protected override AdvancedDropdownItem BuildRoot()
{
var root = new AdvancedDropdownItem("Select Type");
AddTo(root, types);
return root;
}
protected override void ItemSelected(AdvancedDropdownItem item)
{
base.ItemSelected(item);
if (item is SerializeReferenceDropdownItem dropdownItem)
{
onItemSelected?.Invoke(dropdownItem);
}
}
static string[] GetSplittedTypePath(Type type)
{
int splitIndex = type.FullName.LastIndexOf('.');
if (splitIndex >= 0)
{
return new string[] { type.FullName[..splitIndex], type.FullName[(splitIndex + 1)..] };
}
else
{
return new string[] { type.Name };
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: fc340cedf3cee4da19aae647ce6299ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,318 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace Alchemy.Editor
{
internal static class SerializedPropertyExtensions
{
public static bool TryGetAttribute<TAttribute>(this SerializedProperty property, out TAttribute result) where TAttribute : Attribute
{
return TryGetAttribute(property, false, out result);
}
public static bool TryGetAttribute<TAttribute>(this SerializedProperty property, bool inherit, out TAttribute result) where TAttribute : Attribute
{
TAttribute attribute = GetAttribute<TAttribute>(property, inherit);
result = attribute;
return attribute != null;
}
public static TAttribute GetAttribute<TAttribute>(this SerializedProperty property, bool inherit = false) where TAttribute : Attribute
{
if (property == null) throw new ArgumentNullException(nameof(property));
return property.GetFieldInfo().GetCustomAttribute<TAttribute>(inherit);
}
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this SerializedProperty property, bool inherit) where TAttribute : Attribute
{
if (property == null) throw new ArgumentNullException(nameof(property));
return property.GetFieldInfo().GetCustomAttributes<TAttribute>(inherit);
}
public static float GetHeight(this SerializedProperty property)
{
return EditorGUI.GetPropertyHeight(property, true);
}
public static float GetHeight(this SerializedProperty property, bool includeChildren)
{
return EditorGUI.GetPropertyHeight(property, includeChildren);
}
public static float GetHeight(this SerializedProperty property, GUIContent label, bool includeChildren)
{
return EditorGUI.GetPropertyHeight(property, label, includeChildren);
}
public static T GetValue<T>(this SerializedProperty property)
{
return GetNestedObject<T>(property.propertyPath, GetSerializedPropertyRootObject(property), true);
}
public static bool SetValue<T>(this SerializedProperty property, T value)
{
object obj = GetSerializedPropertyRootObject(property);
var fieldStructure = property.propertyPath.Split('.');
for (int i = 0; i < fieldStructure.Length - 1; i++)
{
obj = GetFieldOrPropertyValue<object>(fieldStructure[i], obj);
}
var fieldName = fieldStructure.Last();
return SetFieldOrPropertyValue(fieldName, obj, value);
}
static readonly Regex IndexerRegex = new(@"[^0-9]+");
public static FieldInfo GetFieldInfo(this SerializedProperty property)
{
object target = property.serializedObject.targetObject;
var splits = property.propertyPath.Split('.');
var fieldInfo = ReflectionHelper.GetField(target.GetType(), splits[0], includingBaseNonPublic: true);
target = fieldInfo.GetValue(target);
for (var i = 1; i < splits.Length; i++)
{
if (target == null) return null;
if (splits[i] == "Array")
{
i++;
if (i >= splits.Length) continue;
var index = int.Parse(IndexerRegex.Replace(splits[i], string.Empty));
var targetType = target.GetType();
if (targetType.IsArray) target = (target as Array).GetValue(index);
else target = (target as IList)[index];
i++;
if (i >= splits.Length) continue;
targetType = target.GetType();
fieldInfo = ReflectionHelper.GetField(targetType, splits[i], includingBaseNonPublic: true);
}
else
{
var targetType = target.GetType();
fieldInfo = ReflectionHelper.GetField(targetType, splits[i], includingBaseNonPublic: true);
}
target = fieldInfo?.GetValue(target);
}
return fieldInfo;
}
public static Type GetPropertyType(this SerializedProperty property, bool isCollectionType = false)
{
var fieldInfo = property.GetFieldInfo();
if (isCollectionType && property.propertyType != SerializedPropertyType.String)
return fieldInfo.FieldType.IsArray ?
fieldInfo.FieldType.GetElementType() :
fieldInfo.FieldType.GetGenericArguments()[0];
return fieldInfo.FieldType;
}
public static object SetManagedReferenceType(this SerializedProperty property, Type type)
{
var obj = (type != null) ? Activator.CreateInstance(type) : null;
property.managedReferenceValue = obj;
return obj;
}
public static string GetManagedReferenceFieldTypeName(this SerializedProperty property)
{
var typeName = property.managedReferenceFieldTypename;
var splitIndex = typeName.IndexOf(' ');
return typeName[(splitIndex + 1)..];
}
public static Type GetManagedReferenceFieldType(this SerializedProperty property)
{
var typeName = property.managedReferenceFieldTypename;
var splitIndex = typeName.IndexOf(' ');
var assembly = Assembly.Load(typeName[..splitIndex]);
return assembly.GetType(typeName[(splitIndex + 1)..]);
}
static UnityEngine.Object GetSerializedPropertyRootObject(SerializedProperty property)
{
return property.serializedObject.targetObject;
}
static T GetNestedObject<T>(string path, object obj, bool includeAllBases = false)
{
var parts = path.Split('.');
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part == "Array")
{
var regex = new Regex(@"[^0-9]");
var countText = regex.Replace(parts[i + 1], "");
if (!int.TryParse(countText, out var index))
{
index = -1;
}
obj = GetElementAtOrDefault(obj, index);
i++;
}
else
{
obj = GetFieldOrPropertyValue<object>(part, obj, includeAllBases);
}
}
return (T)obj;
}
static object GetElementAtOrDefault(object arrayOrListObj, int index)
{
if (arrayOrListObj is IEnumerable<object> referenceEnumerable)
{
return referenceEnumerable.ElementAtOrDefault(index);
}
if (arrayOrListObj is IList valueList)
{
object result;
if (index < 0 || index >= valueList.Count)
{
Type listType = valueList.GetType();
Type elementType = listType.IsArray ? listType.GetElementType() : listType.GetGenericArguments()[0];
result = Activator.CreateInstance(elementType);
}
else
{
result = valueList[index];
}
return result;
}
throw new ArgumentException($"Can't parse {arrayOrListObj.GetType()} as Array or List");
}
public static object GetParentObject(this SerializedProperty property)
{
if (property == null) return null;
var path = property.propertyPath.Replace(".Array.data[", "[");
object obj = property.serializedObject.targetObject;
var elements = path.Split('.');
foreach (var element in elements)
{
if (element.Contains("["))
{
var elementName = element[..element.IndexOf("[")];
var index = Convert.ToInt32(element[element.IndexOf("[")..].Replace("[", "").Replace("]", ""));
obj = ReflectionHelper.GetValue(obj, elementName, index);
}
else
{
obj = ReflectionHelper.GetValue(obj, element);
}
}
return obj;
}
public static object GetDeclaredObject(this SerializedProperty property)
{
if (property == null) return null;
var path = property.propertyPath.Replace(".Array.data[", "[");
object obj = property.serializedObject.targetObject;
var elements = path.Split('.');
for (int i = 0; i < elements.Length - 1; i++)
{
var element = elements[i];
if (element.Contains("["))
{
var elementName = element[..element.IndexOf("[")];
var index = Convert.ToInt32(element[element.IndexOf("[")..].Replace("[", "").Replace("]", ""));
obj = ReflectionHelper.GetValue(obj, elementName, index);
}
else
{
obj = ReflectionHelper.GetValue(obj, element);
}
}
return obj;
}
static T GetFieldOrPropertyValue<T>(string fieldName, object obj, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
var field = obj.GetType().GetField(fieldName, bindings);
if (field != null) return (T)field.GetValue(obj);
var property = obj.GetType().GetProperty(fieldName, bindings);
if (property != null) return (T)property.GetValue(obj, null);
if (includeAllBases)
{
foreach (var type in TypeHelper.GetBaseClassesAndInterfaces(obj.GetType()))
{
field = type.GetField(fieldName, bindings);
if (field != null) return (T)field.GetValue(obj);
property = type.GetProperty(fieldName, bindings);
if (property != null) return (T)property.GetValue(obj, null);
}
}
return default;
}
static bool SetFieldOrPropertyValue(string fieldName, object obj, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
var field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
field.SetValue(obj, value);
return true;
}
var property = obj.GetType().GetProperty(fieldName, bindings);
if (property != null)
{
property.SetValue(obj, value, null);
return true;
}
if (includeAllBases)
{
foreach (var type in TypeHelper.GetBaseClassesAndInterfaces(obj.GetType()))
{
field = type.GetField(fieldName, bindings);
if (field != null)
{
field.SetValue(obj, value);
return true;
}
property = type.GetProperty(fieldName, bindings);
if (property != null)
{
property.SetValue(obj, value, null);
return true;
}
}
}
return false;
}
}
}
Loaded 100 of 2211 files, more files were not shown because too many files have changed in this diff. Show more