Unity新版图集SpriteAtlas使用

1,418 阅读2分钟

介绍

unity从2017版本推出了新版的图集系统SpriteAtlas,但是因为项目的原因一直没有使用过。最近新开了一个项目,而且我把unity版本更新到了2020,旧版的图集系统已经被抛弃了,所以尝试使用了新版的SpriteAtlas,现在项目上线了,记录一下SpriteAtlas的使用方法。

本文使用unity版本是2020.1.17,可能不同版本有不同的设置

使用前提

在ProjectSetting-Editor中,将图集模式设置为Sprite Atlas V1 - Always Enable

image.png

使用步骤

在Project面板右键-创建一个SpriteAtlas,然后把需要打包的图或者文件夹直接拖到Objects for Packing中。然后点击Pack Preview就可以看到打包好的图集。

参数介绍

  • Type:图集类型,一般为Master(主体图集),如果需要为不同分辨率设置不同缩放的图集,那就设置为Variant(变体图集)
  • Include in Build:可在当前构建中包含精灵图集资源,默认勾上
  • Allow Rotation:是否可以旋转,默认勾上,可以最大限度提高组合后的纹理中的精灵密度
  • Tight Packing:根据精灵轮廓而非默认矩形轮廓来打包精灵,默认勾上,如果要在UGUI中使用图集,那就别勾了,否则会显示其他精灵的边
  • Padding:精灵图集中各个精灵纹理之间的像素数 其他参数就不介绍了,跟Sprite的参数意思是一样的

image.png

脚本使用方式

//读取项目中的SpriteAtlas
SpriteAtlas spriteAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(spriteAtlasPath);

//创建新的SpriteAtlas
SpriteAtlas spriteAtlas = AssetDatabase.CreateAsset(spriteAtlas, spriteAtlasPath);

//设置参数
SpriteAtlasPackingSettings packingSetting = new SpriteAtlasPackingSettings()
{
    enableRotation = true,
    enableTightPacking = false
};
spriteAtlas.SetPackingSettings(packingSetting);
        TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings()
{
    maxTextureSize = 2048,
    format = TextureImporterFormat.Automatic,
    crunchedCompression = true,
    textureCompression = TextureImporterCompression.Compressed,
    compressionQuality = 50,
};
spriteAtlas.SetPlatformSettings(platformSetting);

//往图集中添加文件夹或者文件
Object[] packables = spriteAtlas.GetPackables();
Object obj = AssetDatabase.LoadAssetAtPath(”文件夹或者文件的路径“, typeof(Object));
if (Array.IndexOf(packables, obj) == -1)
{
    spriteAtlas.Add(new[] { obj });
}