假设有一张png/tga图集,导入到Unity,放置目录"Assets/Resources/UI"(UI文件夹可替换成其他的,重要的是要在"Assets/Resources/"路径下),默认为如下设置:
为了可以使用Unity自带的精灵切割,要将纹理类型改成"
Sprite","
Sprite Mode"改成"
Multiple","
Format"改成"
Truecolor",点击"
Apply"按钮进行应用。
![](https://i-blog.csdnimg.cn/blog_migrate/dd0a153db66f43ddbd22dc638b84a74c.png)
接着,点击"
Sprite Editor"打开精灵编辑器,点击左上角的"
Slice"按钮,弹出切片设置,再次点击里面的"
Slice"按钮,就会自动对图片进行切割,如下图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/5cf10d8435de8b53e04181ddcacd2606.png)
在对切割不完整的地方进行修正后,点击右上角的"
Apply"按钮,进行保存。可以看到Project视图下这个图集,已经被分割出许多小图了,如下图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/60e45ddae718e4a948084064fd3e1ec8.png)
接下来,因为要对图片进行读写操作,要更改图片的属性才能进行,否则会提示如下:
- UnityException: Texture 'testUI' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.
将图片纹理类型更改为"
Advanced",将"
Read/Write Enabled"属性进行打勾,如下图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/e2b285f51ccad8b0fc1d2ec0763e530d.png)
创建一个脚本文件,代码如下:
using UnityEngine;
using UnityEditor;
public class TestSaveSprite
{
[MenuItem("Tools/导出精灵")]
static void SaveSprite()
{
foreach (Object obj in Selection.objects)
{
string selectionPath = AssetDatabase.GetAssetPath(obj);
var allAssets = AssetDatabase.LoadAllAssetsAtPath(selectionPath);
foreach (var asset in allAssets)
{
if (asset is Sprite)
{
// 创建导出文件夹
string outPath = Application.dataPath + "/outSprite/" + System.IO.Path.GetFileNameWithoutExtension(selectionPath);
if (!System.IO.Directory.Exists(outPath))
{
System.IO.Directory.CreateDirectory(outPath);
}
var sprite = asset as Sprite;
// 创建单独的纹理
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文件
System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
}
}
}
Debug.Log("SaveSprite Finished");
}
}
在Unity编辑器将会看到Tools菜单下多了" 导出精灵"项,选中图集,然后点击" 导出精灵"菜单项,即可导出子图成功。如下图所示: