- Home /
Displaying the whole list in a single Text
I'm a beginner to Unity, and want to make one sheet of input history, which is expected to show as (1, 2, 1, 2, 3,....) endlessly. But I can only pick one of numbers from the list, stating by mylist[1] in order. Is there any way I can state the whole list, and display as a Text?
GameObject counter;
public List<int> brain = new List<int>();
// Use this for initialization
void Start () {
this.counter = GameObject.Find("Counter");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
brain.Add(1);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
brain.Add(2);
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
brain.Add(3);
}
counter.GetComponent<Text>().text = brain[0].ToString();
}
Answer by Mister-Mortal · Nov 24, 2016 at 08:35 AM
Use this method to convert your list to string:
private string ListToText(List<int> list)
{
string result = "";
foreach(var listMember in list)
{
result += listMember.ToString() + "\n";
}
return result;
}
Use it like this:
counter.GetComponent<Text>().text = ListToText(brain);
Thank you so much! So, you could convert the list to string! This did not work on my script, so I'll study on "ListToText" because I will need it! :)
@daccithechopper I forgot to add semicolon after "\n". Should do the job now.
Answer by BackslashOllie · Nov 24, 2016 at 08:36 AM
What you need is a for or a foreach loop.
Please see below a quick example of using a foreach loop
GameObject counter;
public List<int> brain = new List<int>();
// Use this for initialization
void Start()
{
this.counter = GameObject.Find("Counter");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
brain.Add(1);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
brain.Add(2);
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
brain.Add(3);
}
counter.GetComponent<Text>().text = ""; //Clear the text
foreach (int item in brain) //Add each item to the text
counter.GetComponent<Text>().text += item.ToString() + ", ";
}
Thank you so much! The foreach loop worked just as I wanted. I was blindly just trying to get the whole list in the script, I should have tried to add to the text by myself, like this :)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Linq OrderBy GameObject's name Numerical 1 Answer
How to Sync List 1 Answer
How can I continue to instantiate an object after deleting 0 Answers
Change Variable Value by List Number 1 Answer