I am loading a byte[ ] from a web resource, which means that I want to do that operation at most one time per application run.
The byte[ ] is a single PNG image that will eventually become a Sprite by way of a Texture2d.
Assume (for example’s sake only) that I keep a reference to the byte[ ] in a static variable. I am assuming that it takes some non-trivial amount of processing time to turn the byte[ ] into a texture (via the Texture2d.LoadImage method). Finally, I am not sure of the processing time required to associate said Texture2d object with a Sprite object (via Sprite.Create)
My two specific questions are: (a) Can I safely load the Texture2d object and the Sprite object in a separate Thread than the main Unity processing thread (e.g. a ThreadPool thread); and (b) Can I keep a reference to a Texture2d object and/or a Sprite object between scenes (as in another static variable) without introducing weird memory management issues or other issues that may not be obvious when switching scenes, regardless of which thread they were created on?
You can’t use any of the Unity API in separate threads (it’s not a matter of safely or not, Unity actively prevents it). Even if it was possible, you should always do things in the most straightforward manner first; don’t make assumptions and don’t prematurely optimize especially with something as complex as multithreaded code. Use DontDestroyOnLoad to keep scripts and their variables when loading a new scene.
OK so the threadpool is out, but my second question wasn’t answered. I know how to use DontDestroyOnLoad , what I’m curious about is when it is and when it is not appropriate to use it.
For instance, If I maintain a reference to a Texture2d object and use DontDestroyOnLoad, is that Texture kept in the GPU during scenes when it is not in use? Alternatively, can I use that Texture2d object safely in any scene I like, or can I only use it in the scene that it was created in, therefore requiring me to re-load a new Texture2d object in each and every scene containing that image I loaded from the WWW?