Accesing specific int from inspector
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.
You need C# reflection
I cant quite get how it works, can you provide a example code? @Hellium Thanks
I have never used it myself, but you will find posts with examples like this one : https://forum.unity3d.com/threads/access-variable-by-string-name.42487/
Answer by Hellium · Feb 04, 2017 at 06:23 PM
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);
I forgot to indicate that you must add using System.Reflection
at the top of your file.
AND :
THATValue = GetIntValue( "thing1" ) ;
I did add using System.Reflection; BUT this is still not working:
BTW REALLY sorry for your time, I really appreciate it ;) Thank you
Answer by KureKureciCZ · Feb 04, 2017 at 08:17 PM
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);
}
}