Skip to content

Commit e31dedb

Browse files
committed
Added an extension method to check if a property is in an array or not.
1 parent af60bfa commit e31dedb

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Scripts/Editor/Extensions/SerializedPropertyExtensions.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Collections.Generic;
44
using System.Linq;
55
using System.Reflection;
6+
using System.Text.RegularExpressions;
67
using UnityEditor;
78
using UnityEngine;
89
using Object = UnityEngine.Object;
@@ -301,5 +302,49 @@ static T DescendHierarchy<T>(object targetObject, List<string> splitName, List<i
301302

302303
return DescendHierarchy<T>(newObj, splitName, splitCounts, depth + 1);
303304
}
305+
306+
/// <summary>
307+
/// From: https://gist.github.com/monry/9de7009689cbc5050c652bcaaaa11daa
308+
/// </summary>
309+
public static SerializedProperty GetParent(this SerializedProperty serializedProperty)
310+
{
311+
string[] propertyPaths = serializedProperty.propertyPath.Split('.');
312+
if (propertyPaths.Length <= 1)
313+
return default;
314+
315+
SerializedProperty parentSerializedProperty =
316+
serializedProperty.serializedObject.FindProperty(propertyPaths.First());
317+
for (int index = 1; index < propertyPaths.Length - 1; index++)
318+
{
319+
if (propertyPaths[index] == "Array")
320+
{
321+
// Reached the end
322+
if (index + 1 == propertyPaths.Length - 1)
323+
break;
324+
325+
if (propertyPaths.Length > index + 1 && Regex.IsMatch(propertyPaths[index + 1], "^data\\[\\d+\\]$"))
326+
{
327+
Match match = Regex.Match(propertyPaths[index + 1], "^data\\[(\\d+)\\]$");
328+
int arrayIndex = int.Parse(match.Groups[1].Value);
329+
parentSerializedProperty = parentSerializedProperty.GetArrayElementAtIndex(arrayIndex);
330+
index++;
331+
}
332+
333+
continue;
334+
}
335+
336+
parentSerializedProperty = parentSerializedProperty.FindPropertyRelative(propertyPaths[index]);
337+
}
338+
339+
return parentSerializedProperty;
340+
}
341+
342+
public static bool IsInArray(this SerializedProperty serializedProperty)
343+
{
344+
SerializedProperty parent = serializedProperty.GetParent();
345+
if (parent == null)
346+
return false;
347+
return parent.isArray;
348+
}
304349
}
305350
}

0 commit comments

Comments
 (0)