自己做项目在搜集资源的时候会碰到把很多UI集成到一张png图片的情况,例如这样的,一种很智障的精灵图保存形式,没有其他文件来存储每个小图的位置信息:
这个时候我们会将图片的Texture Type改为Sprite(2D and UI),Sprite Mode改为Multiple,然后用 SpriteEditor将其分割成小图,生成图集以供UGUI使用,但是如果我们用NGUI的话就需要小的图片来制作图集,这个时候我们可以用这个插件导出小的图片。
这个插件是根据前辈们写的基础来做的,但是做的过程中可能因为unity版本不一致的问题,format设置很多时候会报错,但是不修改format我也没看出什么影响,所以我就改成适用于自己工程的插件了。
关于图片分割部分就不细说了,分割完成后图片设置一下然后Apply
完成的效果是这样的:
接下来需要写一段代码,编写SaveSprite.cs文件并将其放入Assets下的Editor文件夹中,没有的话就自己建一个Editor文件夹,然后把图片资源放入自己工程Resources文件夹的目录中,没有就自己建
SaveSprite.cs脚本代码:
using UnityEngine;
using UnityEditor;
using System.IO;
public class SaveSprite
{
[MenuItem("Tools/SaveSprite")]
static void BeginSaveSprite()
{
string resourcesPath = "Assets/Game/Resources/";//存入Resources路径
string cur_outPath = "Texture/Atlas/";
bool isSuccessSaved = false;
foreach (Object obj in Selection.objects)
{
//选择图片的绝对路径,我的是"Assets/Game/Resources/Texture/Atlas/testUI.png"
string selectionPath = AssetDatabase.GetAssetPath(obj);
// 必须最上级是"Assets/Game/Resources/"
if (selectionPath.StartsWith(resourcesPath))
{
string selectionExt = System.IO.Path.GetExtension(selectionPath);//拿到文件后缀.png
if (selectionExt.Length == 0)
{
continue;
}
// 从路径"Assets/Game/Resources/Texture/Atlas/testUI.png"得到路径"Texture/Atlas/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 + "/Game/Resources/Texture/DiabloUISprite/" + loadPath.Substring(cur_outPath.Length);
System.IO.Directory.CreateDirectory(outPath);
foreach (Sprite sprite in sprites)
{
Debug.Log(sprite.name);
// 创建单独的纹理
Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);
var pixels = sprite.texture.GetPixels((int)sprite.textureRect.x,
(int)sprite.textureRect.y, (int)sprite.textureRect.width,
(int)sprite.textureRect.height);
tex.SetPixels(pixels);
tex.Apply();
// 写入成PNG文件
System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
}
isSuccessSaved = true;
}
}
}
if (isSuccessSaved)
{
Debug.Log("SaveSprite Successed!");
}
else
{
Debug.LogError("SaveSprite Failed!");
}
}
}
然后我们在unity菜单栏可以看到Tools目录下有个SaveSprite,选中要导出小图的图集,点击一下SaveSprite就会将图片导出至一个文件夹,这个导出文件夹的路径可以根据自己工程在脚本中修改,但是图片资源路径必须在Resources文件加下,如果有什么特殊需求的话也可以自己写文件读取。
导出完就这样式的: