I am using Unity's native sprite editor to slice up a texture as a spritesheet. I would like to be able to then get an array of all the sprite slice via scripting.
For example I would like to have a SpriteSheet class that could be used like this.
class MyClass
// Drag sprite sheet from assets to this inspector slot.
public SpriteSheet spritesheet;
void Awake() {
foreach(Sprite sprite in spritesheet.sprites) {
... do something with sprite
}
}
}
But it seems that the sprite sheet is nothing more than a Texture2D with a .meta associated with it. There is a TextureImporter class that has a spritesheet property but how do I access the TextureImporter during runtime? Even if I could access during EditTime I could use it to populate a Sprite[] which right now is being maintained by hand, which is painful for hundreds of sprites.
Any advice would be appreciated.
Once you have a reference to a texture 2d:
Texture2D texture = ...;
you could do something like this:
string path = AssetDatabase.GetAssetPath(texture);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
List < SpriteMetaData > newData = new List < SpriteMetaData > ();
for (int i = 0; i < ti.spritesheet.Length; i++) {
SpriteMetaData d = ti.spritesheet[i];
//do whatever you want with the metadata...
newData.Add(d);
}
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
this is a portion of a script posted here.