- Home /
How to access var in other class using string
I'm trying to access a variable in a different script using a string specified in the inspector:
//PSEUDOCODE
objective = myGameManager."objectiveToPick";
But this obviously doesn't work and I don't know how to pass the string as a variable name and use it to acces the property in the manager script.
I found methods using Hashtables, Dictionary's etc but they don't work and they seem above my current level of scripting.
Is it possible to do this and if so, how?
Are there any easy methods to do so?
Does this impact performance a great deal?
What I need it for:
I am creating a object that displays a text above a npc. The message differs based on whether the objective was completed or not. The objective is a boolean inside a manager script. I want to use this script on multiple objects and check for different objectives.
I want to assign the objective variable in the inspector as a string then acces it using a reference to the gameManager script. So I declare the required variables specify the objective in the inspector and try the following in the start function:
// PSEUDOCODE
public var objectiveToPick : String;
private var myGameManager : sc_GameManager;
private var objective : boolean;
function Start (){
myGameManager = GameObject.Find("GameManager").GetComponent(sc_GameManager);
objective = myGameManager."objectiveToPick"; // doesn't work, but I want to specify the variable using a string
}
function Update(){
if(objective == false)
Debug.Log("Objective isn't completed");
else if(objectiveTo == true)
Debug.Log("Objective completed");
}
I'm using unityscript but feel free to post any C# answers. Thanks in advance
Found a way to solve the problem using the answer in this thread:
http://answers.unity3d.com/questions/207095/construct-variable-name-from-strings.html
It uses reflection though and thus is slow. But since I only use it when entering a trigger it seems usable enough.