using System.Collections;
using System.Reflection;
using UnityEditor;
namespace Ubisoft
{
///
/// Class containing a collection of UnityEditor related utilities.
///
public class HtUnityEditorUtility : Editor
{
///
/// Gets the object the property represents, typically to be used in a PropertyDrawer.
/// Taken from https://github.com/lordofduct/spacepuppy-unity-framework/blob/master/SpacepuppyBaseEditor/EditorHelper.cs.
///
/// SerializedProperty to retrieve the object from.
/// Object that the property represents.
public static object GetTargetObjectOfProperty(SerializedProperty prop)
{
if (prop == null)
{
return null;
}
var path = prop.propertyPath.Replace(".Array.data[", "[");
object obj = prop.serializedObject.targetObject;
var elements = path.Split('.');
foreach (var element in elements)
{
if (element.Contains("["))
{
var elementName = element.Substring(0, element.IndexOf("["));
var index = System.Convert.ToInt32(element.Substring(element.IndexOf("[")).Replace("[", "").Replace("]", ""));
obj = GetValue_Imp(obj, elementName, index);
}
else
{
obj = GetValue_Imp(obj, element);
}
}
return obj;
}
private static object GetValue_Imp(object source, string name)
{
if (source == null)
{
return null;
}
var type = source.GetType();
while (type != null)
{
var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (f != null)
{
return f.GetValue(source);
}
var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (p != null)
{
return p.GetValue(source, null);
}
type = type.BaseType;
}
return null;
}
private static object GetValue_Imp(object source, string name, int index)
{
#pragma warning disable IDE0019 // Use pattern matching
IEnumerable enumerable = GetValue_Imp(source, name) as IEnumerable;
#pragma warning restore IDE0019 // Use pattern matching
if (enumerable == null)
{
return null;
}
IEnumerator enm = enumerable.GetEnumerator();
//while (index-- >= 0)
// enm.MoveNext();
//return enm.Current;
for (int i = 0; i <= index; i++)
{
if (!enm.MoveNext())
{
return null;
}
}
return enm.Current;
}
}
}