Can't access object parent type if some parent object along the way was in array

I use this method to get type of the object the field was declared via reflection. (f.e.) this time it's field at index [5] - activePlaybackAudioArchive.

If along the way the object/objects in hierarchy was placed in array it produces - [1] Array and [2] data[0]. Strangely the [SerializeField] private AudioPlayerData[] _audioPlayerData is the array, why it shows in hierarchy below this variable is unusual to me.

Is there a good way to deal with this problem, or omit the indices like [1] and [2]? Or maybe there is a proper way to get fieldNames that wouldn't include Array like types into path?

• I wouldn't like to have exceptions that are omitted because they can appear out of nowhere, so I didn't bother making them because it would be a faster fix and look like code smell. But this is reflection, so I guess there may not be another way but to parse strings in fieldNames array. – Candid Moon _Max_ Mar 19 '18 at 18:58

public static readonly string[] PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS = { "Array", "data[" };

private static bool IsException(string fieldName)
{
for (int j = 0; j < TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS.Length; j++)
if (fieldName.Substring(0, TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS[j].Length) == TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS[j])
return true;

return false;
}

/// <summary>
/// Search to top of the hierarchy via fieldNames
/// </summary>
/// <param name="type"></param>
/// <param name="fieldNames"></param>
/// <returns>Parent object FieldInfo || null if has no parent</returns>
public static FieldInfo GetParentObjectFieldInfoViaPath(this Type type, string[] fieldNames)
{
FieldInfo fieldInfo = null;

for (int i = 0; i < fieldNames.Length - 1; i++)
{
//if (TypeExtensions.IsException(fieldNames[i]))
//  continue;
if (type.IsArray)
{
type = type.GetElementType();

i += 2;
}

fieldInfo = type.GetField(fieldNames[i], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

if (fieldInfo.FieldType.IsArray && i + 3 >= fieldNames.Length)
break;

type = fieldInfo.FieldType;
}

return fieldInfo;
}


Here is a quick workaround, cheat :) Check if it's an array, if it is, then skip 2 steps (Array, data[n]). Then the magic method - GetElementType() and everything is fine.

• Please paste code as text, not as images. That keeps it searchable, copy & paste friendly, and accessible to users via screen readers. – DMGregory Oct 9 '18 at 23:10