1

Every time I load a texture from a saved file, any animation in my scene is frozen until the loading from file is done. I read so many different opinions about Threads, and none got answers. but I have to load the texture in a different thread to avoid freezing. My code is attached to a gameobject which is a UI popup window

void Start() {
Texture2D tex = LoadTexFromFile(); //Should be in a diffrent thread that returns a texture
sprite = Sprite.Create(tex, 
                       new Rect(0, 0, tex.width, tex.height), 
                       new Vector2(tex.width / 2, tex.height / 2));

picFrame.GetComponent<Image>().overrideSprite = sprite; }

How do I safely use threads in my code?

SHAI
  • 789
  • 3
  • 10
  • 43
  • Possible duplicate of [Android Unity - Load a file on background thread](https://stackoverflow.com/questions/54234452/android-unity-load-a-file-on-background-thread) – Maifee Ul Asad Apr 14 '19 at 02:09
  • Not a duplicate. Also, that user didn't get answers. – SHAI Apr 14 '19 at 17:02
  • I was thinking then why @Michał Powłoka ticked that answer then ? – Maifee Ul Asad Apr 14 '19 at 17:26
  • He answered his own question with a workaround because people didn't answer him. Also, the way he reads file is different than my code, I don't have access to LoadTexFromFile() and he found a workaround on the reader itself which I don't have access to – SHAI Apr 14 '19 at 17:29

1 Answers1

0

Best practices say that you should not load assets during a level but rather at the start so as to avoid disruption. Why are you going against what middleware like Unity provides? Let it manage your assests for you and load them at the start of the level.

There is a use-case (not specific for Unity) for asset streaming but is generally reserved for AAA on-demand asset loading such as textures; mesh; and other assets in say large open-world games but I doubt this is the case here. Such a feature is highly complicated and I won't go into it here.

Tell me more

enter image description here

  • Thanks for your answer. I can't load everything at the start, because it's a lot of tex screenshot to load on the memory for nothing. My scene is a map, and every level stores a screenshot texture. When clicking on a level, a saved texture should be loaded from a file. If I start loading all the screenshots from all levels at the start it'll take a long time for the scene to start, which is the case already. That's why I want to separate the loading texture on a different thread – SHAI Apr 14 '19 at 01:20
  • @SHAI sounds to me that your game assets are not optimsed _per level_. Unity is there to do this sort of thing for you. If you find this isn't the case then there is something wrong –  Apr 14 '19 at 01:26