1
\$\begingroup\$

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[]?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Why couldn't you use System.IO? Have you even tried? It's totally fine to use it. \$\endgroup\$
    – Hellium
    Dec 11, 2017 at 19:34
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – xuwenbuwer
    Dec 11, 2017 at 19:42

1 Answer 1

3
\$\begingroup\$

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)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .