So I want to make a script that’ll report back the value of variable (either an Int or Float) based off what is written in a string variable. I’d be able to do this with a bunch of separate scripts, but I want to be able to make one script where I just type in the variable name that I want to grab. I’ll be using this to pull variables from the Player Prefs.
I’m thinking something along these lines, but it would actually work. I just don’t know how to grab a variable’s value based off of a string…
var variableName = "";
var variableTemp = 0.0;
var variable1 = 1.1;
var variable2 = 2.2;
function GrabVariable () {
variableTemp = **"variableName"** <---- that's what I don't know how to do.
print(variableTemp);
}
Any help would be awesome.
Thanks.
Use C# reflection. You can google it but what you do is something like this:
MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public);
foreach (MethodInfo methodInfo in methodInfos)
{
if( methodInfo.Name == "MyVaraible" )
{
Debug.Log( "VALUE " + methodInfo.ToString() );
}
}
You can also iterate over a class’ properties, privates, statics, etc…
You could try using reflection. I haven’t used reflection in javascript before but it might work something like this.
function GrabVariable( owner : object, variableName : string )
{
var variableInfo : FieldInfo = owner.GetType().GetField( variableName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
if ( variableInfo == null )
{
Debug.LogWarning("No varibale in class " + owner.GetType() + " called " + variableName + ".");
return null;
}
return variableInfo.GetValue( owner );
}
I don’t even know if you can use reflection in javascript so here’s the c# version
public static object GrabVariable( object owner, string variableName )
{
FieldInfo variableInfo = owner.GetType().GetField( variableName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
if ( variableInfo == null )
{
Debug.LogWarning("No varibale in class " + owner.GetType() + " called " + variableName + ".");
return null;
}
return variableInfo.GetValue( owner );
}
You can potentially do that using reflection, but it’s better to use an array.
var variableNumber = 0;
var variableTemp = 0.0;
var variables = [1.1, 2.2];
function GrabVariable () {
variableTemp = variables[variableNumber];
}
If you really want to use a name, you could also use a Dictionary (which is like a hashtable, which you can also use, but Dictionary is better).