Hi,
I have this function:
showDialogBox("minVar", 60, "objMaster");
function showDialogBox (varName, varLength, objectName) {
//connect til variablen
var master_dialog_script : masterDialogScript;
master_dialog_script = GetComponent (masterDialogScript);
//assign text to dialog box
myText = GameObject.Find("/GUI/GUI_dialogText/dialog");
myText.guiText.text = master_dialog_script.varName;
//show final dialog box
ShowTex("/GUI/GUI_dialogText#withChildren#on");
}
which works fine, apart from this line:
myText.guiText.text = master_dialog_script.varName;
If I write this instead it works perfectly:
myText.guiText.text = master_dialog_script.minVar;
This is because there actually exists a variable name minVar in the master_dialog_script. The problem is that when I write master_dialog_script.varName
it of course tries to access a variable called varName in the master_dialog_script instead of actually evaluating varName to its true value minVar.
Trouble is that I want to be able to call the function with different variable-names. But how do I do that?
You can’t append your string (passed as varName) as a dot-property of your master_dialog_script object (as you’ve found out). What you might try instead is to create a simple accessor function inside your master_dialog_script that checks the string provided and returns the specific value:
function GetProperty (aPropName) {
if (aPropName == "minVar") {
return minVar;
} else if (...) {
...
}
}
Then in your code example above, instead of accessing the property directly, you call your accessor function instead:
myText.guiText.text = master_dialog_script.GetProperty(varName);
It is possible to access variables dynamically by name using .Net’s introspection features. But this is usualy not the right way to approach the problem.
The way your code looks, it seems you are trying to use an object as a dictionary of strings. Instead of seperate variables, you should store all the strings inside a single hash table.
// in masterDialogScript.js
var messages = {
"minVar": "The message for minVar",
"maxVar": "The message for maxVar",
"mediumVar": "The message for medimVar" };
Then in the showDialogBox function, instead of master_dialog_script.varName, write:
myText.guiText.text = master_dialog_script.messages[varName];