导入Asset时自动标记Addressable

需求

就算可以批量勾选Addressable并管理分组,也希望有一个自动化工具,可以在导入Asset的时候就标记Addressable并根据所在文件夹分组。

于是用到AssetPostprocessor。

解决方案

思路如下:

  1. 使用OnPostprocessAllAssets函数,遍历importedAssets,判定Asset所在路径;

  2. 获取Asset的AddressableAssetEntry,如果存在,则跳过当前循环;

  3. 根据path获取Asset所在文件夹名,检测是否存在同名的AddressableAssetGroup,如果不存在,则根据文件夹名创建分组;

  4. 使用AddressableAssetSettings.CreateOrMoveEntry函数创建Entry,然后移动至对应的分组中,并将Address设置为文件名,等同于Simplify Addressable Names。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class AddressableAssetPostprocessor : AssetPostprocessor
{
public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths, bool didDomainReload)
{
AddressableAssetSettings aaSettings = AddressableAssetSettingsDefaultObject.GetSettings(true);
foreach (var path in importedAssets)
{
if (!path.Contains("UI/Atlas/"))
{
continue;
}

string guid = AssetDatabase.AssetPathToGUID(path);
AddressableAssetEntry entry = aaSettings.FindAssetEntry(guid);
if (entry != null)
{
continue;
}

string parent = Path.GetDirectoryName(path);
string folder = Path.GetFileNameWithoutExtension(parent);
string[] groups = aaSettings.groups.Select(x => x.Name).ToArray();
if (!groups.Contains(folder))
{
var localGroup = aaSettings.CreateGroup(folder, false, false, false, null, typeof(ContentUpdateGroupSchema), typeof(BundledAssetGroupSchema));
var schema = localGroup.GetSchema<BundledAssetGroupSchema>();
schema.BuildPath.SetVariableByName(aaSettings, AddressableAssetSettings.kLocalBuildPath);
schema.LoadPath.SetVariableByName(aaSettings, AddressableAssetSettings.kLocalLoadPath);
schema.BundleMode = BundledAssetGroupSchema.BundlePackingMode.PackTogether;
}

var group = aaSettings.FindGroup(folder);
entry = aaSettings.CreateOrMoveEntry(guid, group, false, true);
entry.SetAddress(Path.GetFileNameWithoutExtension(entry.address), false);
}
}
}

文档链接

Class AddressableAssetEntry

Class AddressableAssetSettings