- Home /
How to find a variable with a string?
I have a script where there are different static variables and a string variable. I want to know if I could make it so then someone could type in the name of one of the static variables and then it could be modified like that. For example, I will use this script:
static var apples = 0;
static var coconuts = 5;
var variableName : String;
function Update(){
if(Input.GetKeyDown("mouse 1")){
//This is where I would want either apples or coconuts to be modified
}
}
Answer by aldonaletto · Dec 24, 2013 at 02:36 AM
You can't use web javascript tricks like defining a variable name based on a string variable, but this behaviour can be simulated to a certain extent - for instance:
static var apples = 0;
static var coconuts = 5;
var variableName : String;
function Update(){
if(Input.GetKeyDown("mouse 1")){
switch(variableName){
case "apples":
apples++;
break;
case "coconuts":
coconuts++;
break;
}
}
}
Answer by KellyThomas · Dec 24, 2013 at 03:11 AM
If you have a finite set of variables, and they are known at design time then there are better approaches.
However if there are unknowns reflection can get the job done:
#pragma strict
import System.Reflection;
static var coconuts = 5;
var apples = 1;
function getFieldValue(name: String) {
var field : FieldInfo = this.GetType().GetField(name, BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance);
if (field != null) {
return field.GetValue(this);
}
return null;
}
function setFieldValue(name: String, value: Object) {
var field : FieldInfo = this.GetType().GetField(name, BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance);
if (field != null) {
field.SetValue(this, value);
}
}
function Start(){
//static
Debug.Log("coconuts: " + getFieldValue("coconuts"));
setFieldValue("coconuts", 10);
Debug.Log("coconuts: " + getFieldValue("coconuts"));
//instance
Debug.Log("apples: " + getFieldValue("apples"));
setFieldValue("apples", 8);
Debug.Log("apples: " + getFieldValue("apples"));
}
Your answer
Follow this Question
Related Questions
Calling non applied scripts 3 Answers
The variables and functions 2 Answers
Modifying a shader color dynamicly through another script 0 Answers
Declaring animations on a script in the editor 1 Answer
Changing variables in another script 3 Answers