- Home /
ArrayLists giving wrong information? C#
Hello there,
I am trying to make an Dialogue system(I dont want to use any plugins as this is a learning procces for me). But the ArrayLists are giving me other information then expected. This is my code:
private ArrayList Questions = new ArrayList();
private ArrayList Answers = new ArrayList();
//public Texture CharacterTexture;
void Start () {
Answers.Add("Doorgaan?");
Answers.Add("nee");
Answers.Add("ja");
Questions.Add(Answers);
Answers.Clear();
Answers.Add("En wat nu weer?");
Answers.Add("aaaa");
Answers.Add("bbbb");
Questions.Add(Answers);
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
if(GUI.Button(new Rect(Screen.width / 2 - 150,250,300,50),((ArrayList)Questions[0])[0].ToString())){
Debug.Log("Je hebt nu op nr 0 geklikt");
}
if (GUI.Button(new Rect(Screen.width / 2 - 150, 300, 300, 50), ((ArrayList)Questions[0])[1].ToString()))
{
Debug.Log("Je hebt nu op nr 1 geklikt");
}
if (GUI.Button(new Rect(Screen.width / 2 - 150, 350, 300, 50), ((ArrayList)Questions[0])[2].ToString()))
{
Debug.Log("Je hebt nu op nr 2 geklikt");
}
Now I expect 'Questions[0])[0]' to display "Doorgaan?", 'Questions[0])[1]' "Nee" etc. But instead it is showing me "en wat nu weer?", "aaaa" and "bbbb".. How can I fix it? What am I doing wrong in my code?
Thank you for your time :)
Answer by yatagarasu · Nov 26, 2013 at 05:39 PM
You should allocate new Array, not Clear the old one.
void Start () {
Answers.Add("Doorgaan?");
Answers.Add("nee");
Answers.Add("ja");
Questions.Add(Answers);
Answers = new ArrayList();
Answers.Add("En wat nu weer?");
Answers.Add("aaaa");
Answers.Add("bbbb");
Questions.Add(Answers);
}
Since he looses the reference to first set of answers, this is effectively the same.
I see what I did wrong, you're right. It's a reference to the Answers array, and I clear it, and simply put new data in it, that's why it showed the last answers I added. Thanks!
Answer by Lovrenc · Nov 26, 2013 at 05:41 PM
Since this is a learning project i dont know how much of a "spoiler" answer you want.
However, your problem is in your data structure. You have one Answers list for all your questions. This wont work. You need a set of answers for every question.
So why do you get these results. You used
Answers.Clear();
and cleared the list => you lost the answers for 1st question.
Your answer
Follow this Question
Related Questions
Can anyone help me with a system that helps me to access data inside of data? 2 Answers
Using a list of arrays to make Unity UI 2D button toggle colors 0 Answers
My loop keeps producing the same wrong result :,,( 2 Answers
What do you think of this? List, Vector 3 and Update 1 Answer
Linear Interpolation of Array Values 1 Answer