I am trying to read a binary file from the resources. To do this I call the Resources.Load(..) function getting a TextAsset. Since here everything clear (or maybe not...). But then how can I open it to read? I tried all combinations to be able to read it with the BinaryReader tool but no way. Anybody knows the exact combination?
I already solved this issue. The problem was that the binary file had to have the .txt extension to be able to read it as a TextAsset :)
TextAsset asset = Resources.Load("enemy_seq_bin") as TextAsset;
Stream s = new MemoryStream(asset.bytes);
BinaryReader br = new BinaryReader(s);
Answering your question, the reason to have that file in binary is to speed up the resources loading.
Fun fact I noticed from another answer is that you have to use “.bytes” extension instead of “.txt” for a real binary asset to be loaded with full length. Ref: http://unity3d.com/support/documentation/Components/class-TextAsset.html
Rename binary files to use bytes extension, then something like:
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
TextAsset textAsset = Resources.Load(fileNameWithoutExtension) as TextAsset;
Stream stream = new MemoryStream(textAsset.bytes);
BinaryFormatter formatter = new BinaryFormatter();
MyClass myInstance = formatter.Deserialize(stream) as MyClass;
Then simply may wrap it all into a factory method, like:
public static MyClass LoadFromResources(string fileName)
{ ... }
By the way, there’s a way for the Editor to do the renaming automatically for you (useful if you e.g. use a different editor to edit this files).
See this post for more info.
Since I just had the same problem even though this is a quite old topic:
If you cannot rename the files anymore, because it would mean a huge architectural change, you can consider reencoding them “correctly”.
string utf8String = Encoding.UTF8.GetString(textAsset.bytes);
bytes = Encoding.ASCII.GetBytes(utf8String);