# How to make a string[] from the words of a file in Unity?

I have .txt file containing all the English words separated by line breaks.

I want to turn them to a string[] so I can easily pick a random one from them.

The way I would do that in normal C# is the File.ReadAllLines(path) function in the System.IO namespace.

But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string.

But, if I have a giant string how can I simply split it up into individual words and store them as a string[]?

• Why couldn't you use System.IO? Have you even tried? It's totally fine to use it. – Hellium Dec 11 '17 at 19:34
• Have you ever taken a look at a built Unity project? The Asset folder in the editor contains your files, but when you build your project all your assets get packed into weird package files. But, maybe I am not familiar enough with the System.IO class and you are correct. – IronPig Dec 11 '17 at 19:42

You can split a string into substrings with String.Split.

When you don't have any whitepsaces in that textfile but line breaks (as in no words with spaces in them) you can use

string[] words = yourTextAsset.text.Split();


When you do have whitespaces, use the solution from this stackoverflow question:

string[] words = yourTextAsset.text.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);


(or instead of that hardcoded array with all kinds of line separator flavors, figure out which one is used in your text file)