- Home /
How to properly load textures?
Hello everyone I have this particular problem where I don't know how to load and reference a texture in a prototype I'm making.
I want to be able to procedurally generate level, depending on a texture. This texture is located on a folder where there is other informations about the level (name, size, etc.), stored in JSON text files. Loading those files is easy using deserialization. There could be hundred of different levels, so hundred of folders containing different textures.
How can I load and reference a particular texture given the correct folder among the others?
Is using many "Resources" folders the only solution?
Answer by Dave-Carlile · Sep 12, 2017 at 08:49 PM
You can load image data using Texture2D.LoadImage.
You can get the image data into a byte array using File.ReadAllBytes.
Answer by guido-paglie · Sep 11, 2017 at 07:53 PM
Hi !
Yes, it seems it's the only solution. I think the names should be something
Level-1
Level-2
....
Level-11
Level-36
.....
Level-101
Then you can:
Resources.Load("LevelTextures/Level-" + level) as Texture;
And also you can have in another folder the jsons, and so almost the same to get them.
Resources.Load("LevelJsons/Level-" + level) as TextAsset;
Hope it helps, cheers !
Thanks guido-paglie for your answer ! As I was saying, getting the JSONs files and referencing them doesn't imply Resources folder.
var serializedData = File.ReadAllText(path);
var storedData = JsonUtility.FromJson<T>(serializedData);
I need the same kind of logic to read an image into a texture given a path.
I found something that is Texture.LoadImage but the documentation seems missing and I didn't succeed to make it work.
Any thoughts?
Sorry, but i dont understand what you need.
If you need to read the pixels of the texture ? If you do you need to do a render texture, and then read that pixels.
If you just need to get the sprite (2D) from resources you can:
public Image img;
void Start () { img.sprite = Resources.Load< Sprite >("LevelTextures/Level-" + level ); }
If you are using a 3d model, and you want to put the image you are reading, onto that model, you have to do almost the same but assign it to the mainTexture of the material. And this texture is going to be a texture (haha) not a sprite, because is 3d, not 2d.
public $$anonymous$$eshRenderer renderer;
void Start () { renderer.material.mainTexture = Resources.Load< Texture >("LevelTextures/Level-" + level); }
Hope it helps!