In my game I have a class, where is an array with questions classified according to level. I have 15 levels, so there are 15 arrays. Arrays are naming question1, question2 … question15. And I have a string variable, where I connect a string with number of the level. Here is a part of my code, for better understand what is my problem: (code is in JavaScript)
var question : String = "question" + level.ToString; //here is connecting a string with a number
otherArray[0] = question[0, 0]; //"question" string is a variable, look at line above
But it does not work, I try also give question to print() or write question + number, but nothing, is possible connect those two words and then give it as name of an array? Thanks for any help.
I considered posting this as comment, because @Jamora and @ShadoX were first and their advices are ok. But finally I decided to post as answer, because I do understand the question, and I have a full solution.
When you define a variable inside a class, you have to access this variable by its name directly. You can’t assign the variable name to other variable, like you did, and then use it the way you did. Your code is similar to this one:
var aaa : String = "FirstString";
var bbb : String = "aaa";
print(bbb); // this will print aaa and not FirstString
There’s no direct way to use bbb variable to print FirstString. There is an indirect way (reflection), but this is different topic.
What you need, is Dictionary. This way, you can assign arrays of you questions to particular levels. Sample code:
import System.Collections.Generic;
var dicQuestionsByLevel : Dictionary.<int, String[]>;
function Awake()
{
dicQuestionsByLevel = new Dictionary.<int, String[]>();
var questions : String[];
// level 1
questions = new String[2];
questions[0] = "Level1: first question";
questions[1] = "Level1: econd question";
dicQuestionsByLevel.Add(1, questions);
// level 2
questions = new String[3];
questions[0] = "L2: 1st question";
questions[1] = "L2: 2nd question";
questions[2] = "L2: 3rd question";
dicQuestionsByLevel.Add(2, questions);
// and so on...
}
function Update()
{
print(GetRandomQuestionForLevel(2));
}
function GetRandomQuestionForLevel(level : int)
{
var questions = dicQuestionsByLevel[level];
var index : int = Random.Range(0, questions.Length);
return questions[index];
}