Unity实现自定义图集(一)

以下内容是根据Unity 2020.1.0f1版本进行编写的

Unity自带有图集工具,包括旧版的图集(设置PackingTag),以及新版的图集(生成SpriteAtlas)。一般来说,unity自带的图集系统已经够用了,但是实际使用上还是存在一些可优化的地方,例如加载到Canvas上的资源,打图集不能同时设置TightPacking和AllowRotation,即打图集不能旋转。

此外,也可以更加深入地了解图集的运行逻辑,以及ui材质球的合批。

1、先看看两种打图集方法的效果

关于unity是怎么打图集的,这里有一个链接可以参考:
SpriteAtlas图集预览算法:MaxRectsBinPack
本文是基于这个基础上进行改动的。
按照上述博文的内容,先简单尝试一下,实现其中的内容,效果:
图片资源(资源为网络资源):

Unity的SpriteAtlas打出来的图集:
在这里插入图片描述
根据博文得到的图集:
在这里插入图片描述
(代码中有5种不同的匹配方式,实际结果都大同小异)
可以看到,unity打出来的图集会比上述博文中打出来的图集更小。细看一下发现,是Unity会自动把一些资源周围的空白像素裁掉。

2、旋转资源

先简单做一个ui预制和一个场景预制,都是用相同的资源做的(上面是ui,下面是SpriteRenderer)
在这里插入图片描述
然后把图集改成可旋转
在这里插入图片描述
可以看到部分资源旋转了
接下来运行unity
在这里插入图片描述
可以看到,上半部分ui的界面部分资源方向不对,甚至还把其它资源重叠显示了。

3、接入一个简单的资源加载系统

此处不是重点,简单过一遍,跳过。

using UnityEngine;
/// <summary>
/// 单例类父类
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T:new()
{
   
    private static readonly object _lock = new object();
    private static T _instance;

    protected Singleton()
    {
   
        Debug.Assert(_instance == null);
    }

    public static bool Exists
    {
   
        get
        {
   
            return _instance != null;
        }
    }

    public static T Instance
    {
   
        get
        {
   
            if (_instance == null)
            {
   
                lock (_lock)
                {
   
                    if (_instance == null)
                    {
   
                        _instance = new T();
                    }
                }
            }
            return _instance;
        }
    }
}

实现单例类Singleton

using UnityEngine;

public class GameController : MonoBehaviour
{
   
    void Start()
    {
   
#if UNITY_EDITOR
			AssetsCache.Instance.Init(ResourceLoadMode.Direct);
#else
			AssetsCache.Instance.Init(ResourceLoadMode.AssetBundle);
#endif
	}
}

新建一个游戏管理类GameController,用于初始化资源加载器。
然后在场景上新建一个空节点,命名为Scripts,将GameController挂载到该节点上。
此时可以把canvas下的预制删掉了,如下图:
在这里插入图片描述

using UnityEngine;

public class TestView : MonoBehaviour
{
    const string viewPath = "Assets/Prefabs/testview_myimage.prefab";
    GameObject viewPrefab;
    GameObject canvas;

    void Start()
    {
        canvas = GameObject.Find("Canvas");
        AssetsCache.Instance.GetResource(viewPath, OnGetView);
    }

    void OnGetView(AssetsResource asset)
    {
        viewPrefab = Instantiate(asset.GetAsset(viewPath), canvas.transform) as GameObject;
    }
}

新建一个类TestView,用于加载ui预制到Canvas节点下,并将其挂载到刚刚创建的Scripts节点上:
在这里插入图片描述
在这里插入图片描述
保存场景,运行unity,可以看到预制正常加载出来了。

4、实现一个简单的打包逻辑

此处也不是重点,简单过一遍。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class AppConst
{
   
    // 素材目录 
    public const string AssetDir = "StreamingAssets";

    //打包时需要每个子文件夹打一个bundle的目录
    private static List<string> subDirectoryBundlePaths;
    //打包时需要每个文件打一个bundle的目录
    private static List<string> eachFileBundlePaths;
    //打包时需要将整个文件夹打一个bundle的目录
    private static Dictionary<string, string> wholeDirectoryBundlePaths;

    private static bool hasInit = false;

    public static void Init()
    {
   
        subDirectoryBundlePaths = new List<string>();
        eachFileBundlePaths = new List<string>();
        wholeDirectoryBundlePaths = new Dictionary<string, string>();
        wholeDirectoryBundlePaths.Add("prefab.bundle", "Prefabs/");
        hasInit = true;
    }

    public static List<string> GetSubDirectoryBundlePaths()
    {
   
        if(!hasInit)
        {
   
            Init();
        }
        return subDirectoryBundlePaths;
    }

    public static List<string> GetEachFileBundlePaths()
    {
   
        if (!hasInit)
        {
   
            Init();
        }
        return eachFileBundlePaths;
    }

    public static Dictionary<string, string> GetWholeDirectoryBundlePaths()
    {
   
        if (!hasInit)
        {
   
            Init();
        }
        return wholeDirectoryBundlePaths;
    }

    public static Hashtable GetResourcesHashTable()
    {
   
        Hashtable tb = new Hashtable();
        foreach(var path in GetSubDirectoryBundlePaths())
        {
   
            DirectoryInfo[] directories = new DirectoryInfo(Application.dataPath + path).GetDirectories();
            foreach (var directory in directories)
            {
   
                string assetsPath = UnifyPath(directory.FullName).Substring(7);
                tb[directory.Parent.Name + "." + directory.Name + ".bundle"] = assetsPath;
            }
        }
        foreach (var path in GetEachFileBundlePaths())
        {
   
            List<FileSystemInfo> files = new List<FileSystemInfo>();
            SeachFile(Application.dataPath + path, files, new string[] {
    ".png", ".jpg", ".jpeg", ".tga" });
            foreach (var file in files)
            {
   
                string assetsPath 
### 关于Unity图集批量处理的方法 #### 使用Sprite Atlas API实现自动化脚本 为了应对不同版本间的差异,可以利用Unity提供的`SpriteAtlas`API来编写自定义的编辑器脚本来实现图集的批量处理。对于从旧版向新版迁移的情况,可以通过读取带有相同`PackingTag`标签的纹理资源并将其分配给新的`SpriteAtlas`对象。 ```csharp using UnityEngine; using UnityEditor; public class SpriteAtlasBatchProcessor : EditorWindow { private string atlasName = "NewAtlas"; [MenuItem("Tools/Create Sprite Atlas")] public static void CreateWindow() { GetWindow<SpriteAtlasBatchProcessor>("Sprite Atlas Batch Processor"); } void OnGUI() { GUILayout.Label("Enter the name of your new sprite atlas:", EditorStyles.boldLabel); atlasName = EditorGUILayout.TextField(atlasName); if (GUILayout.Button("Generate")) Generate(); } void Generate(){ Object[] textures = Selection.objects; // 获取当前选择的对象 var assetPath = AssetDatabase.GenerateUniqueAssetPath($"Assets/Resources/{atlasName}.spriteatlas"); SpriteAtlas spriteAtlas = ScriptableObject.CreateInstance<SpriteAtlas>(); foreach(var texture in textures){ TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)); if(importer != null && !string.IsNullOrEmpty(importer.spriteID)){ spriteAtlas.Add(new[]{texture}); } } AssetDatabase.CreateAsset(spriteAtlas, assetPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } ``` 此段代码展示了如何创建一个简单的编辑器窗口用于生成指定名称的新图集,并允许用户选取多个材质贴图作为输入源[^1]。 #### 利用第三方插件加速工作流程 除了官方API外,还有许多社区开发的工具可以帮助更高效地管理图集。例如有开发者分享了一款功能丰富的图集编辑器,它不仅能够支持基本的增删查改操作,还特别加入了针对大规模项目的优化特性,比如按名字筛选特定条目等功能[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值