需要先去下载texturepacker
texturepacker官网:https://www.codeandweb.com/texturepacker
texturepacker是一个打图集的软件,不只是适用于Unity,其他的也能用,用texturepacker来打图集比用Unity自带的打图集工具更好用。
在Unity中新建一个Editor文件夹,再新建一个AutoTPBuild.cs,通过编辑器代码控制自动打图集。
代码如下:
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class AutoTPBuild : Editor
{
//需要打图集的图片路径
private static readonly string _sourceTexturePath = Application.dataPath + "/Source";
//图集的输出路径,没带图集名
private static readonly string _tpOutPath = Application.dataPath + "/Altas/";
//TexturePacker.exe所在位置
private static readonly string _texturePackerExePath = @"E:\TexturePacker\bin\TexturePacker.exe";
[MenuItem("Tools/TPBuild")]
public static void Build()
{
//需要打图集的图片路径下可能有好几个文件夹,每个文件夹中有不同的需要打图集的图片
string[] folders = Directory.GetDirectories(_sourceTexturePath);
string name;
string sheetPath;//图集的输出路径,带图集名
ProcessStartInfo info;
foreach (string folder in folders)
{
name = Path.GetFileName(folder);
sheetPath = $"{_tpOutPath}{name}";
info = GetStartInfo(_texturePackerExePath, GetCommand(sheetPath, folder));
ExcuteProcess(info);
}
AssetDatabase.Refresh();
}
/// <summary>
/// 打图集的所需的命令行
/// </summary>
/// <param name="sheetPath">图集的输出路径,带图集名</param>
/// <param name="folderPath">图片所在文件夹的路径</param>
/// <returns></returns>
private static string GetCommand(string sheetPath,string folderPath)
{
StringBuilder sb = new StringBuilder();
AddSubCommand(sb, $"--sheet {sheetPath}.png");
AddSubCommand(sb, $"--data {sheetPath}.tpsheet");
AddSubCommand(sb, "--format unity-texture2d");
AddSubCommand(sb, "--trim-mode Polygon");
AddSubCommand(sb, "--algorithm Polygon");
AddSubCommand(sb, "--max-size 2048");
AddSubCommand(sb, "--size-constraints POT");
AddSubCommand(sb, $"{folderPath}");
return sb.ToString();
}
/// <summary>
/// 添加命令行
/// </summary>
/// <param name="sb"></param>
/// <param name="command"></param>
private static void AddSubCommand(StringBuilder sb,string command)
{
sb.Append(" ");
sb.Append(command);
}
/// <summary>
/// 返回一个执行TexturePacker.exe的带有打图集命令的进程
/// </summary>
/// <param name="exePath"></param>
/// <param name="command"></param>
/// <returns></returns>
private static ProcessStartInfo GetStartInfo(string exePath, string command)
{
ProcessStartInfo info = new ProcessStartInfo(exePath);
info.Arguments = command;
info.ErrorDialog = true;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
return info;
}
/// <summary>
/// 执行打图集的进程
/// </summary>
/// <param name="info"></param>
private static void ExcuteProcess(ProcessStartInfo info)
{
Process process = Process.Start(info);
Debug.Log(process.StandardOutput.ReadToEnd());
string error = process.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Debug.LogError(error);
}
process.Close();
}
}
上面那几个路径要指定好,自己根据自身情况来写路径。
之后点击Tools/TPBuild就可以自动打图集了。