I have a normal non-script component class (ie. does not inherit from MonoBehaviour, no Awake, Start funcs, etc) and I'm using it to parse and load text file assets, but I keep getting an error: "You are not allowed to call get_text when declaring a variable". Is there some problem using Resources.Load from outside of a Unity script?
{
StringReader reader = null;
TextAsset textAsset = (TextAsset)Resources.Load(stringTableName, typeof(TextAsset));
// blah, error checking
// read the strings from file and insert into the hash table
reader = new StringReader(textAsset.text);
The error happens on the line where I create the StringReader to parse the file. I mean, this is simply a normal class, so it can only be called from script, right? And by the time that a script component is able to create/call functions from this class, unity should be all set up and ready to go, so I'm not sure what the problem is.
No, you can call it from (almost) anywhere, the issue is that you're assigning when you're declaring it as a member field
What you need to do is assign to it in the constructor probably:
public class YourClass
{
TextAsset textAsset;
public YourClass()
{
textAsset = (TextAsset)Resources.Load(stringTableName, typeof(TextAsset));
}
}
This may not fix it if the class is being created in a similar way though (i.e. at someplace other than inside an event function called from unity), so at that point you may just need to put the assign into whichever functions use it, after checking if it's null, e.g.
public void Test()
{
if (textAsset == null)
{
textAsset = (TextAsset)Resources.Load(stringTableName, typeof(TextAsset));
}
}
This is a commercial project, so I don't know if I can post any of the specific code, but I've found that even when trying a cut down test class, with the exact same form, that the error doesn't occur.
The test class is:
public class TempClass
{
static TempClass m_TempClass;
List<string> m_StringList;
StringReader reader;
private static TempClass Instance
{
get
{
if (m_TempClass == null)
{
m_TempClass = new TempClass();
}
return m_TempClass;
}
}
public static TempClass GetInstance()
{
return Instance;
}
private TempClass()
{
m_StringList = new List<string>();
}
public static string LoadString(string fileName)
{
TempClass tempClass = GetInstance();
string temp = ParseFile(fileName);
return temp;
}
static string ParseFile(string fileName)
{
string temp;
TextAsset textAsset = (TextAsset)Resources.Load(fileName, typeof(TextAsset));
Instance.reader = new StringReader(textAsset.text);
temp = Instance.reader.ReadLine();
for (;
temp != null;
temp = Instance.reader.ReadLine())
{
Instance.m_StringList.Add(temp);
}
return temp;
}
}
I don't know how much help it will be to see the code that works, but I'm hoping it sparks something. I've found that in the actual code, the error occurs during the usage of 'textAsset.text' If I replace that with a string literal, then the script compile error doesn't occur.