- Home /
Creating a String Array from a text file,Creating a StringArray from a TextAsset
Alright, so I have this text file containing a bunch of words separated by a new line.
I intend to drag and drop this text file into Unity inspector, and then store the words inside into a string array.
Here's what I have done:
public TextAsset asset;
public static string[] wordList = asset.text.Split('\n');
It's giving me an error, which could be fixed by making TextAsset asset static. But then I won't be able to access it through the Inspector.
Apologies if this is a really newbie question. Can't seem to find a way out...
Answer by Harinezumi · Mar 19, 2018 at 08:20 AM
You are getting this error, because you are trying to assign value at the declaration of a static member variable ( wordList
) by processing a non-static variable ( asset
). That is, a compile-time operation (assignment to static field) run on a run-time specified variable.
Instead, just declare wordList
without assigning it a value, then assign the words from asset
in Awake()
of a script, or if it is in a regular class, in the constructor of the class.
Sweet, got it well and working. Thanks a lot, especially the info about compile-time VS run-time.
Sure, I'm glad I could help! :)
In general, you can only assign compile-time values at the declaration of a member variable (e.g. null
, concrete values like 0
, -1
, 3.14f
, string literals like "some text"
, or array "initializers" { 1, 1, 2, 3, 5, 8 }
), or initializing it by instantiating a type with new
.