- Home /
Loop through string? (foreach new line)
Hi.
Is there a C# script that makes it possible to make a for loop that loops through a string each new line.
For example if we have a string like this (with 2 lines):
A dog
A cat
I would like a for loop that can loop though the lines and for example instantiate a gameobject with the name 'A dog' or 'A cat'.
Please tell me if this isn't explained correctly.
Thank you very much.
Answer by superbsumit · Aug 26, 2014 at 06:51 PM
Not tested..but it should work :
public GameObject go;
string[] Array = yourText.Split("\n" [0]);
for (int i = 0; i< Array.Length ; i++) {
GameObject someObject = (GameObject)Instantiate(go);
someObject.name = Array[i];
}
Answer by fueldown · Aug 26, 2014 at 06:29 PM
If you are reading that from a file, I suggest you to use the CSV and parse the csv with buffered reader.
If you are not, then this is very odd thing to do. you may need to breakdown the string using some special character to separate the lines and saving it in string array. Then iterate that array with foreach / for loop.
Thanks for your answer.
It's because I'm getting the string using the WWW class and there is one word on each line. I then want to create a GameObject for each line with a name according to the string on that line. I hope this makes more sense.
@brianruggieri is right. I was suggesting the same thing, but wasn't sure if newline character (\n or \r still not sure) can be used with String.Split. If you can, then that's the way to go. If not, and you have access to changing what you can receive, you may want to change the newline to a special character and use that with String.Split.
A Cat|A Dog|...
Answer by roojerry · Aug 26, 2014 at 06:32 PM
String.Split with the newline character will give you an array of strings that you could then loop through
Assu$$anonymous$$g the newline character is \n :
foreach (string line in String.Split(myString, "\n"))
{
GameObject obj = new GameObject(line);
}