I am trying to make a class helper to create dynamically objects using a ScriptableObject as config file for parameters needed for the constructor of each object I want to create. At runtime the GetType() returns a valid type/object ref if inspected then generates errors internally see the pictures. I’ll be grateful if anyone can point me to where or how to diagnose this issue.
public static T ParseProperties<T>(ScriptableObject configSO, string objectName, params string[] propertyNames) where T : class
{
if (configSO == null) return null;
Type configType = configSO.GetType();
Type targetType = typeof(T);
if (string.IsNullOrEmpty(objectName)) return null;
// Create a dictionary to hold parsed property values
Dictionary<string, object> parsedValues = new();
foreach (var propName in propertyNames)
{
//var propInfo = configSO.GetType().GetField(propName);
var propInfo = configType.GetField(propName);
if (propInfo != null)
{
parsedValues.Add(propName, propInfo.GetValue(configSO));
}
}
// Create an object of the target type dynamically
if (targetType.Name.Equals(objectName))
{
return CreateObject(targetType, parsedValues) as T;
}
return null;
}
private static object CreateObject(Type targetType, Dictionary<string, object> parsedValues)
{
// Check for a constructor that matches all the parsed values
ConstructorInfo constructor = null;
var constructors = targetType.GetConstructors();
foreach (var ctor in constructors)
{
var parameters = ctor.GetParameters();
if (parameters.Length == parsedValues.Count)
{
bool match = true;
foreach (var parameter in parameters)
{
if (!parsedValues.ContainsKey(parameter.Name))
{
match = false;
break;
}
}
if (match)
{
constructor = ctor;
break;
}
}
}
if (constructor == null)
{
//If no constructor match the property, use an object creation without params
return Activator.CreateInstance(targetType);
}
else
{
List<object> paramValues = new();
foreach (var parameter in constructor.GetParameters())
{
paramValues.Add(parsedValues[parameter.Name]);
}
return constructor.Invoke(paramValues.ToArray());
}
}
}