1.导入一张PNG图集放置目录"Assets/Resources/UI/ball.png"下
2.将ball.png选中修改Texture Type为Sprite(2D and UI),Sprite Mode改为Multiple,点击Apply按钮进行应用。
接着,点击Sprite Editor打开精灵编辑器,点击左上角的Slice按钮,弹出切片设置,再次点击里面的Slice按钮,就会自动对图片进行切割,点击右上角的Apply按钮,进行保存。会产生切割出来的小图片。
3.然后再选中ball.png,将图片纹理类型更改为Advanced,将"Read/Write Enabled"属性进行打勾。
4.在Assets新建一个目录Editor,在里面创建一个TestSaveSprite.cs脚本
using UnityEngine;5.选中ball.png,点击菜单栏Tools/导出Sprites,即可生成单张图片
using UnityEditor;
using System.IO;
public class TestSaveSprite
{
[MenuItem("Tools/导出Sprites")]
static void SaveSprite()
{
string resourcesPath = "Assets/Resources/";
foreach (Object obj in Selection.objects)
{
string selectionPath = AssetDatabase.GetAssetPath(obj);
// 必须最上级是"Assets/Resources/"
if (selectionPath.StartsWith(resourcesPath))
{
string selectionExt = Path.GetExtension(selectionPath);
if (selectionExt.Length == 0)
{
continue;
}
// 从路径"Assets/Resources/UI/testUI.png"得到路径"UI/testUI"
string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
loadPath = loadPath.Substring(resourcesPath.Length);
// 加载此文件下的所有资源
Sprite []sprites = Resources.LoadAll<Sprite>(loadPath);
if (sprites.Length > 0)
{
// 创建导出文件夹
string outPath = Application.dataPath + "/outSprite/" + loadPath;
Directory.CreateDirectory(outPath);
foreach (Sprite sprite in sprites)
{
// 创建单独的纹理
Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false);
tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin,
(int)sprite.rect.width, (int)sprite.rect.height));
tex.Apply();
// 写入成PNG文件
File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
}
Debug.Log("SaveSprite to " + outPath);
}
}
}
Debug.Log("SaveSprite Finished");
}
}