Prior to upgrading to Unity 3, code similar to the following was used to load binary resource files at runtime. The resource files stored in the Resources folder are .RESOURCES files, but the extension has been changed to .XML so they can be read in as TextAssets.
TextAsset textAsset = UnityEngine.Resources.Load("binary_resource_filename") as TextAsset;
MemoryStream ms = new MemoryStream(textAsset.bytes);
ResourceReader rr = new ResourceReader(ms);
ResourceSet rs = new ResourceSet(rr);
Since upgrading to Unity 3, I have been unable to get this code to work, and receive the following error:
ArgumentException: Stream is not a valid .resources file, magic=0x1
System.Resources.ResourceReader.ReadHeaders ()
System.Resources.ResourceReader..ctor (System.IO.Stream stream)
According to a Microsoft document regarding Resources, “The first four bytes of the system default file format contain a 32-bit signed integer in little-endian format.” This “magic number” is 0xBEEFCACE. (ResourceManager.MagicNumber Field (System.Resources) | Microsoft Learn)
Looking at the resource file with a HEX editor shows that it does include the correct 4 bytes, although when I
The first 32 bytes are:
CE CA EF BE 01 00 00 00 9E 00 00 00 29 53 79 73
74 65 6D 2E 52 65 73 6F 75 72 63 65 73 2E 52 65
When I look at the first 16 bytes of the TextAsset that is loaded with statements such as:
Debug.Log(textAsset.bytes[0]);
Debug.Log(textAsset.bytes[1]);
Debug.Log(textAsset.bytes[2]);
… I get the following bytes:
01 00 00 00 00 00 00 29 53 79 73 74 65 6D 2E 52
My guess is that loading the resource file into a TextAsset is stripping out all bytes that are greater than 0x7F, including the necessary “magic number”. When the error reports, “magic=0x1”, I believe it is pointing to the first four bytes after stripping out “CE CA EF BE”.
If this is actually the intended behavior that changed with Unity 3, is there an alternative way to load in a binary resource file as a stream so that it can be passed to ResourceReader()?