Question by
ramSilva · Oct 25, 2016 at 01:22 PM ·
buildspriteunityeditorslice
Slice sprites in a build
I currently have some code that allows me to import an image from an url, create a sprite from it, slice the sprite at runtime and get a one of the slices, all at runtime.
However, all of this funcionality requires the UnityEditor namespace, which isn't available when trying to build the project.
My question is if it is possible to achieve this functionality using some other namespaces, or even external libraries if needed.
The code in question:
void Start() {
StartCoroutine(loadImage("https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png", "Assets/Resources/Sprites/Map/", "map"));
}
IEnumerator loadImage(string url, string path, string name) {
WWW www = new WWW(url);
// Wait for download to complete
yield return www;
Sprite sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0.5f, 0.5f));
sprite.name = name;
File.WriteAllBytes(path + name + ".png", www.texture.EncodeToPNG());
AssetDatabase.Refresh();
AssetDatabase.AddObjectToAsset(sprite, path + name + ".png");
AssetDatabase.SaveAssets();
}
Sprite getSubSpriteAtCoordinate(Sprite sprite, int x, int y, float width, float height) {
string path = AssetDatabase.GetAssetPath(sprite);
string resourcesPath = path.Replace("Assets/Resources/", "").Replace(sprite.name + ".png", "");
string spriteName = x.ToString() + y.ToString() + width.ToString() + height.ToString();
Sprite loadedSprite = Resources.Load<Sprite>(resourcesPath + sprite.name);
if (loadedSprite != null) {
return loadedSprite;
}
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
ti.textureType = TextureImporterType.Sprite;
ti.spriteImportMode = SpriteImportMode.Multiple;
List<SpriteMetaData> newData = new List<SpriteMetaData>(ti.spritesheet);
SpriteMetaData smd = new SpriteMetaData();
smd.pivot = new Vector2(0.5f, 0.5f);
smd.alignment = 9;
smd.name = spriteName;
smd.rect = new Rect(x, y, width, height);
newData.Add(smd);
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
loadedSprite = Resources.Load<Sprite>(resourcesPath + sprite.name);
return loadedSprite;
}
Comment