A have a lot of ints
int thing1;
int thing2;
int thing3;
int thing4;
int thing5;
int SelectedInt;
public string IntToSelect;
If i write the ints name in the strings field in the inspector, it should do this:
SelectedInt = IntToSelect;
Or something similar. But, is there a way, WITHOUT having tons of ifs for every single one of them?
Thanks.
Make sure your integers are declared public
and do the following :
using System.Reflection;
// ...
public int thing1;
public int thing2;
public int thing3;
public int thing4;
public int thing5;
public int GetIntValue( string integerName )
{
System.Type type = GetType();
FieldInfo info = type.GetField(integerName );
if( info == null )
{
throw new System.Exception( "The field " + integerName + " does not exist" );
}
return (int)info.GetValue(this);
}
Use the [HideInInspector]
attribute if you don’t want to see the variables in the inspector
##EDIT :
To get private fields :
FieldInfo info = type.GetField(value,BindingFlags.NonPublic | BindingFlags.Instance);
Here is the whole code for everyone:
using UnityEngine;
using System.Collections;
using System.Reflection;
public class YOURCLASSNAME : MonoBehaviour {
public string ToSelect;
public int Selected;
public int thing1;
public int thing2;
public int thing3;
public int thing4;
public int thing5;
public int GetIntValue(string integerName)
{
System.Type type = GetType();
FieldInfo info = type.GetField(integerName);
if (info == null)
{
throw new System.Exception("The field " + integerName + " does not exist");
}
return (int)info.GetValue(this);
}
void Start() {
Selected = GetIntValue(ToSelect);
Debug.Log(Selected);
}
}