- Home /
Getting texture size off main thread
I have a class called Chunk where I am rendering meshes, and I need to use UV's to get pieces of textures on those meshes, I have a few functions linked to get those UV's, but they need to use the width and height of the texture to do that, I am using a separate thread for all chunk loading stuff for obvious reasons. The problem I am running into is that the textures aren't all the same size and I need to get those sizes, I could hard-code them in, but there are several textures that I am still adding to and I'm adding more textures, so I figured out you can do Material.mainTexture.width/height, but it won't let me do that off the main thread, is there a clever workaround or will I have to hard-code all the sizes in?
Answer by Bunny83 · Apr 26, 2020 at 11:27 PM
Uhm just cache those sizes in your own variables. You can read them once at start on the main thread. Where you store them and how you organise those sizes is up to you. Currently you have to somehow reference the texture in question. Of course that doesn't work on a seperate thread. So instead you use your own variables. What you could use is a Dictionary<Texture, Vector2Int> texSizes
which you populate in Start for all textures you might need. So when you have a texture reference you can simply lookup the size like this:
Vector2Int size;
if (!texSizes.TryGetValue(yourTexture, out size))
throw new System.Exception("Texture size is missing")
// use "size" here
Of course in general it would be better to not touch textures at all from your worker threads. So you might store and reference the sizes in a different way. Though since we have no idea how you choose the texture we can't tell you what you should do.
Yes, this works really well for me, can't believe I didn't think of this! Thanks!