unity sprite怎么获取切割后的图

2015年01月26日 09:16 1 点赞 0 评论 更新于 2025-11-21 15:26

在学习了一段时间的 Unity 之后,我对其中的组件有了大致的了解,但在具体操作方面还不够熟悉。今天我看到一篇关于“Unity Sprite 怎么获取切割后的图”的文章,觉得很有价值,在此分享详细的操作过程。

1. 图集导入与设置

假设有一张 PNG 或 TGA 格式的图集,我们需要将其导入到 Unity 中,并放置在 “Assets/Resources/UI” 目录下(这里的 UI 文件夹可以替换为其他名称,但必须位于 “Assets/Resources/” 路径下)。导入后,图集的默认设置可能不符合我们的需求,需要进行如下修改:

  • 将纹理类型改成 “Sprite”。
  • 将 “Sprite Mode” 改成 “Multiple”。
  • 将 “Format” 改成 “Truecolor”。 修改完成后,点击 “Apply” 按钮应用这些设置。

2. 精灵切割操作

为了对图集进行切割,我们需要使用 Unity 自带的精灵编辑器。具体步骤如下:

  • 点击 “Sprite Editor” 打开精灵编辑器。
  • 在精灵编辑器中,点击左上角的 “Slice” 按钮,此时会弹出切片设置窗口。
  • 在切片设置窗口中,再次点击 “Slice” 按钮,Unity 会自动对图片进行切割。 切割完成后,如果发现有切割不完整的地方,可以进行修正。修正完毕后,点击右上角的 “Apply” 按钮保存切割结果。此时,在 Project 视图下可以看到该图集已经被分割成许多小图。

3. 图片属性更改

由于后续需要对图片进行读写操作,所以要更改图片的属性,否则会出现如下错误提示:

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” 属性。

4. 编写脚本导出切割后的图片

接下来,我们创建一个脚本文件来实现导出切割后图片的功能。脚本代码如下:

using UnityEngine;
using UnityEditor;

public class TestSaveSprite
{
[MenuItem("Tools/导出精灵")]
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 = System.IO.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;
System.IO.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文件
System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
}
Debug.Log("SaveSprite to " + outPath);
}
}
}
Debug.Log("SaveSprite Finished");
}
}

5. 导出子图

将上述脚本保存后,在 Unity 编辑器中会看到 Tools 菜单下多了 “导出精灵” 选项。我们只需要选中之前处理好的图集,然后点击 “导出精灵” 菜单项,即可成功导出切割后的子图。

通过以上步骤,我们就可以在 Unity 中获取并导出 Sprite 切割后的图片了。

作者信息

feifeila

feifeila

共发布了 3994 篇文章