Sprite Mode设置成Multiple 消失

2015年01月31日 10:51 0 点赞 0 评论 更新于 2025-11-21 15:50

今天主要为大家介绍将 Sprite Mode 设置成 Multiple 消失相关问题的入门内容,大家可以参考学习。若有不懂的地方,可到社区提问,我看到后会及时解决。若我未回复,说明已有大神在社区解答。

图片导入与设置

假设有一张 PNG 或 TGA 格式的图集,需将其导入到 Unity 中,并放置在目录 "Assets/Resources/UI" 下(UI 文件夹可替换为其他名称,但必须在 "Assets/Resources/" 路径下)。

为使用 Unity 自带的精灵切割功能,要对图片的纹理属性进行如下修改:

  1. 将纹理类型改成 "Sprite"。
  2. 把 "Sprite Mode" 改成 "Multiple"。
  3. 将 "Format" 改成 "Truecolor"。
  4. 点击 "Apply" 按钮应用上述设置。

精灵切割操作

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

图片读写属性更改

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

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

脚本编写与导出操作

接下来创建一个脚本文件,代码如下:

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");
}
}

在 Unity 编辑器中,会看到 Tools 菜单下新增了 "导出精灵" 项。选中图集后,点击 "导出精灵" 菜单项,即可成功导出子图。

总结

关于将 Sprite Mode 设置成 Multiple 消失的问题就介绍到这里。若大家还有疑问,可到社区提问。