- Home /
Reading texture from texture atlas by name or path
I need to create a texture Atlas dynamically, so I have used Texture2D.PackTextures to pack all textures in a folder named "Images" in my Resources folder.
Texture2D[] atlasTextures = Resources.LoadAll<Texture2D>("Images");
Texture2D atlas = new Texture2D(4096, 4096);
Rect[] rects = atlas.PackTextures(atlasTextures, 2, 4096);
string atlasDirPath = Application.persistentDataPath + "/Resources/Images";
if (!Directory.Exists(atlasDirPath))
{
Directory.CreateDirectory(atlasDirPath);
}
FileStream fs = new FileStream(atlasDirPath+"Atlas.png", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(atlas.EncodeToPNG());
bw.Close();
fs.Close();
So an Atlas Images is perfectly generated and saved in the persistent path. Now, I need to get a particluar texture individually and convert it to sprite and add it to spriteRenderer in my scene. But to select a texture, I only have the name/path of the texture. But Texture2D.PackTextures returns Rect[] array. Now I don't understand how should I pick a particular texture from the atlas with me only having the name of the texture.
Answer by Namey5 · Jun 11, 2021 at 02:18 AM
In theory, the rect array returned from the packing function should match the order of the input textures - as such, if you were to also cache the source textures (or at least some of their data) you would be able to use that and match the textures up with their positions;
Dictionary<string, Rect> m_AtlasTextures = new Dictionary<string, Rect>();
...
Texture2D[] atlasTextures = Resources.LoadAll<Texture2D>("Images");
Texture2D atlas = new Texture2D(4096, 4096);
Rect[] rects = atlas.PackTextures (atlasTextures, 2, 4096);
for (int i = 0; i < atlasTextures.Length; i++)
{
// Cache each texture rect by its corresponding texture name
m_AtlasTextures[atlasTextures[i].name] = rects[i];
}
...
// Then, you can fetch the texture coordinates like so
public Rect GetAtlasTextureCoordsByName (string a_TextureName)
{
return m_AtlasTextures[a_TextureName];
}
I have not tested this, but I can't imagine the rect array not matching the order of the input textures, otherwise the data would be useless - there would be no way of knowing what element a rect would be pointing to.