Question by
UareBuggy · Dec 23, 2016 at 01:03 PM ·
c#componentreflectiontypecomponents
Edit variable of component by type
Hello, I have to create function that will take component by type from gameobject and will update any variable value specified in function parameters. I don't know what component will be edited so it needs to be type.
public void SetProperty<T>(T obj, string valueKey, string value, Type type= null)
{
var typeToUse = type ?? typeof(T);
var pointIndex = valueKey.IndexOf(".", StringComparison.Ordinal);
if (pointIndex!=-1)
{
var subKey = valueKey.Substring(0, pointIndex);
var fieldInfo = typeToUse.GetField(subKey);
var propObj = fieldInfo.GetValue(obj)?? Activator.CreateInstance(fieldInfo.FieldType);
SetProperty(propObj, valueKey.Substring(pointIndex+1), value, fieldInfo.FieldType);
fieldInfo.SetValue(obj, propObj);
}
else
{
var fieldInfo = typeToUse.GetField(valueKey);
if (fieldInfo != null)
fieldInfo.SetValue(obj, value);
}
}
If I'm trying to use function this way, it works
SetProperty(selected.GetComponent<Component>(), "testVar", "Test Name");
If I'm trying to use it this way(and I need to use it this way) it doesn't work.
SetProperty(selected.GetComponent(type), "testVar", "Test Name");
I absolutely don't know why it doesn't work. There is null reference exception in component in function but I really don't know why it is null, because if I try Debug.Log(selected.GetComponent(type));
, it prints me that component.
Comment