您的位置:首页 > 移动开发 > Unity3D

Unity3d-NGUI-一键打包Texurepacker NGUI图集

2016-05-05 20:25 567 查看
NGUI内置图集打包工具,生成的图集效率太低(空白区域太多),并且对图集的可调整性极差。相反Texturepacker支持如Unity、Cocos2d、Flash等多个平台,极丰富的配置参数,如DPI、图片通道格式,对齐算法,允许图集旋转等,提高了游戏中使用贴图的灵活性。





关于如何手动将Texturepacker制作NGUI图集。这里不作介绍。但为了读者对下面内容不感到突兀建议读者先了解该制作过程。

而本文的目的就是介绍如何将这一制作过程自动化。

Unity3D 5.3.3

Texturepacker 3.3.2

NGUI 3.8.2

目录结构

+Assets
+RawResources
+Atlas
+XX
- xx.png
XX.tps
+Resources
+Atlas
-XX.png
-XX.mat
-XX.txt
-XX.prefab


Assets/RawResources/Atlas/美术切图存放根目录

Assets/RawResources/Atlas/XX根目录下区分的游戏模块切图目录

Assets/RawResources/Atlas/XX.tps要目录下区分游戏模块的Texturpacker工程文件

Assets/Resources/Atlas存放NGUI图集目录

static string tpCommand = "D:/CodeAndWeb/TexturePacker/bin/TexturePacker.exe";
static string tpProjectsDir = Application.dataPath + "/RawResource/Atlas/";
static string atlasDir = Application.dataPath + "/Resources/Atlas/";


TexturePacker工程文件

Assets/RawResources/Atlas/下存放各个模块对应的游戏切图Texurepacker工程文件。工程配置项如下,这里仅作参考,务必按照项目要求调整。但有两点需要注意。

1. 并没填写DataFile和TextureFile输出目录。考虑到以后的维护性,选择在代码中决定图集的输出目录更具优势。

2. 不允许Allow rotation。据我所知直至NGUI3.8.2, 并不支持该选项。





打包命令

打包命令只有2项任务,导出Texpacker图集,然后转换成NGUI图集。

/// <summary>
/// 自动构建图集菜单命令
/// </summary>
[MenuItem("GameTools/构建图集")]
public static void BuildAtlas()
{
if (string.IsNullOrEmpty(tpCommand) || !tpCommand.Contains("TexturePacker"))
{
EditorUtility.DisplayDialog("null", "未配置TexturePacker命令路径", "确定");
return;
}
SetupTpAtlas();
SetupNGUIAtlas();
Debug.Log("GameTools/构建图集 结束");
}


导出Texturepacker图集

遍历Assets/RawResources/Atlas下的Texturepacker工程文件。并使用命令
TexturePacKer.exe --data xx.txt --shet xx.png xx.tps
导出图集。关于Texturepacker.exe的命令参数。参见官方说明

https://www.codeandweb.com/texturepacker/documentation

参数输出文件说明
–data.txt、.json等为工程文件缺省的DataFile目录
–sheet.png、.jpg等为工程文件缺少的TextureFile目录
/// <summary>
/// 配置TexturePacker对Unity图集的导出
/// </summary>
private static void SetupTpAtlas()
{
// 打包新图集
try
{
string[] tpsFiles = Directory.GetFiles(tpProjectsDir, "*.tps");

for (int i = 0; i < tpsFiles.Length; ++i)
{
string file = tpsFiles[i];
string tpPath = Path.GetFullPath(file);

EditorUtility.DisplayProgressBar("打包图集", string.Format("正在进行{0}", file), i / tpsFiles.Length);

// 构建Texturepack.exe打包命令参数
string texturePath = string.Format("{0}/{1}.png", atlasDir, Path.GetFileNameWithoutExtension(file));
string txtPath = string.Format("{0}/{1}.txt", atlasDir, Path.GetFileNameWithoutExtension(file));
string args = string.Format("--data \"{0}\" --sheet \"{1}\" \"{2}\"", txtPath, texturePath, tpPath);

// 启动打包命令
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.StandardOutputEncoding = System.Text.Encoding.Default;
process.StartInfo.FileName = tpCommand;
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
string allOutput = process.StandardOutput.ReadToEnd();
process.Close();
}
}
catch (Exception ex)
{
Debug.LogError("Error " + ex.ToString());
}
finally
{
EditorUtility.ClearProgressBar();
}
}


转换到NGUI 图集

构建NGUI图集,需要3个文件。

文件类型作用
.prefab含UIAtlas组件,存放切图在偏移与缩放参数
.mat含2D UI材质,去掉阴影投影,雾化、不光照等配置
.png大图
编码中发现,AssetDataBase创建资源的接口,有几点需要注意,否则创建失败。参见另一篇文章/article/9760730.html

另外,为不影响图片质量减少大小,设置了png的Texture Import属性。如去除minmap,图片只读等。

/// <summary>
/// 配置NGUI图集
/// </summary>
private static void SetupNGUIAtlas()
{
try
{
AssetDatabase.Refresh();
string[] files = Directory.GetFiles(atlasDir, "*.png");

for (int i = 0; i < files.Length; ++i)
{
EditorUtility.DisplayProgressBar("设置NGUI图集", string.Format("正在进行{0}", files[i]), i / files.Length);

// 创建NGUI的3个图集文件
string pngFile = string.Format("{0}/{1}", GlobalDefine.c_ResAtlasDirectory, Path.GetFileName(files[i]));
pngFile.Replace("\\", "/");
string dataFile = Path.ChangeExtension(pngFile, "txt");
string prefabFile = Path.ChangeExtension(pngFile, "prefab");
string matFile = Path.ChangeExtension(pngFile, "mat");

// 加载文件图集文件,如果不存则创建
GameObject prefabAsset = AssetDatabase.LoadMainAssetAtPath(prefabFile) as GameObject;
if (prefabAsset == null)
{
GameObject temp = new GameObject();
prefabAsset = PrefabUtility.CreatePrefab(prefabFile, temp);
GameObject.DestroyImmediate(temp);
}

Material matAsset = AssetDatabase.LoadMainAssetAtPath(matFile) as Material;
if (matAsset == null)
{
matAsset = new Material(Shader.Find("Unlit/Transparent Colored"));
AssetDatabase.CreateAsset(matAsset, matFile);
}

UIAtlas uiAtlas = prefabAsset.GetComponent<UIAtlas>();
if (uiAtlas == null)
uiAtlas = prefabAsset.AddComponent<UIAtlas>();

// 配置图集参数
Texture2D pngAsset = TexturePackerExec.GetAtlasTexture(pngFile);
TextAsset dataAsset = AssetDatabase.LoadMainAssetAtPath(dataFile) as TextAsset;
matAsset.SetTexture("_MainTex", pngAsset);
uiAtlas.spriteMaterial = matAsset;
NGUIJson.LoadSpriteData(uiAtlas, dataAsset);
uiAtlas.MarkAsChanged();
EditorUtility.SetDirty(uiAtlas);
}
}
catch (System.Exception ex)
{
Debug.LogError("Error " + ex.ToString());
}
finally
{
EditorUtility.ClearProgressBar();
}

AssetDatabase.Refresh();
}

/// <summary>
/// 获取NGUI图庥参数项的贴图
/// </summary>
/// <returns>The atlas texture.</returns>
/// <param name="path">Path.</param>
public static Texture2D GetAtlasTexture(string path)
{
if (string.IsNullOrEmpty(path))
return null;

TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
if (ti == null)
return null;

TextureImporterSettings settings = new TextureImporterSettings();
ti.ReadTextureSettings(settings);
settings.readable = false;
settings.maxTextureSize = 4096;
settings.wrapMode = TextureWrapMode.Clamp;
settings.npotScale = TextureImporterNPOTScale.ToNearest;
settings.mipmapEnabled = false;
settings.aniso = 4;
settings.alphaIsTransparency = true;
ti.SetTextureSettings(settings);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);

return AssetDatabase.LoadMainAssetAtPath(path) as Texture2D;


代码链接:http://download.csdn.net/detail/maomaoxiaohuo/9513672
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: