# Problems with the Unity text field

Let say I have this list and currently there are three animals inside the list. These names below are displayed on the text field in the scene.

Cat

Bird

Goat

If there is a new animal is added to the list, for example a 'dog', the code will add 'dog' below the 'Goat' inside the text field above. Now I have a problem when the same animal is added to the list. I don't know how to actually display the updated text field if the same type of animal is added to the list and will not messing up the text field or duplicating the same name inside the text field. Please help.

This is the code

foreach (var animalnames in newComp)
{
if((componentName.text.Length !=0)&&(animal.transform.name != animalnames.name))
{
componentName.text = oldName+('\n')+('\n')+('\n')+animal.transform.name;
}
if((componentName.text.Length !=0)&&(animal.transform.name == animalnames.name))
{
Debug.Log("same");
animalnames.name = animal.transform.name;
//componentName.text = ('\n')+animalnames.name;
}
}
oldName = componentName.text;

• I have 2 question. Is newComp a list? And what exactly do you want to do, like you don't want to show duplicate text or you wanna show duplicate text but at the bottom? – Aditya Yadav Jun 7 '17 at 10:35
• Yes, newComp is a list, and I want to make some sort of list of animals, and yes, I don't want to show duplicate text. – user3132527 Jun 8 '17 at 1:25
• I see that @Xesenix solution worked for you. But I'll leave my suggestion as well. You can use LINQ here. To avoid saving duplicates, just use Contains method to check the text you want to add already exist or not. – Aditya Yadav Jun 8 '17 at 4:57

You should probably use StringBuilder for creating text field content something like this:

// somewhere in component constructor
this.sb = new StringBuilder()
this.animalNamesList = new List<string>()

if (!this.animalNamesList.Contains(name)) {
}

// and in update text field content
this.sb.clear()
foreach (string animalName in this.animalNamesList) {
this.sb.AppendLine(animalName)
}
this.textField.text = this.sb.ToString()


• Thanks for the reply, the code is working except when I try to clear the string with this this.sb.clear(), it doesn't exist. Am I missing something? – user3132527 Jun 7 '17 at 9:51
• If you are using C# 4.0 or higher compiler, you can use string.Join, e.g. text = string.Join("\n\n", newComp.Select(an => an.name)), chaining select with Distinct if you want just distinct values. – wondra Jun 7 '17 at 12:31
• You guys are amazing! I use @Xesenix code and I use Distinct like @wondra suggested and it worked now. Thanks again :) – user3132527 Jun 8 '17 at 1:58