/// <summary>
    /// Get addressable asset entry of an object.
    /// </summary>
    /// <param name="o">>object to recive addressable asset entry</param>
    /// <returns>addressable asset entry</returns>
    public static UnityEditor.AddressableAssets.Settings.AddressableAssetEntry GetAddressableAssetEntry(Object o)
    {
        UnityEditor.AddressableAssets.Settings.AddressableAssetSettings aaSettings = UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings;

        UnityEditor.AddressableAssets.Settings.AddressableAssetEntry entry = null;
        string guid    = string.Empty;
        long   localID = 0;
        string path;

        bool foundAsset = AssetDatabase.TryGetGUIDAndLocalFileIdentifier(o, out guid, out localID);

        path = AssetDatabase.GUIDToAssetPath(guid);

        if (foundAsset && (path.ToLower().Contains("assets")))
        {
            if (aaSettings != null)
            {
                entry = aaSettings.FindAssetEntry(guid);
            }
        }

        if (entry != null)
        {
            return(entry);
        }

        return(null);
    }
Example #2
0
 static void AddEntry(AddressableAssetEntry e, object k, Dictionary <object, HashSet <AddressableAssetEntry> > keyToEntries)
 {
     if (!keyToEntries.TryGetValue(k, out HashSet <AddressableAssetEntry> entries))
     {
         keyToEntries.Add(k, entries = new HashSet <AddressableAssetEntry>());
     }
     entries.Add(e);
 }
 /// <summary>
 /// Get Addressables Key/ID of an object.
 /// </summary>
 /// <param name="o">object to recive addressables Key/ID</param>
 /// <returns>Addressables Key/ID</returns>
 public static string GetAddressableID(this Object o)
 {
     UnityEditor.AddressableAssets.Settings.AddressableAssetEntry entry = GetAddressableAssetEntry(o);
     if (entry != null)
     {
         return(entry.address);
     }
     return("");
 }
        /// <summary>
        /// Gets an entry for this folder entry
        /// </summary>
        /// <param name="subAssetGuid"></param>
        /// <param name="subAssetPath"></param>
        /// <returns></returns>
        /// <remarks>Assumes that this asset entry is a valid folder asset</remarks>
        internal AddressableAssetEntry GetFolderSubEntry(string subAssetGuid, string subAssetPath)
        {
            string assetPath = AssetPath;

            if (string.IsNullOrEmpty(assetPath) || !subAssetPath.StartsWith(assetPath))
            {
                return(null);
            }
            var settings = parentGroup.Settings;

            AddressableAssetEntry assetEntry = settings.FindAssetEntry(subAssetGuid);

            if (assetEntry != null)
            {
                if (assetEntry.IsSubAsset && assetEntry.ParentEntry == this)
                {
                    return(assetEntry);
                }
                return(null);
            }

            string relativePath = subAssetPath.Remove(0, assetPath.Length + 1);

            string[] splitRelativePath = relativePath.Split('/');
            string   folderPath        = assetPath;

            for (int i = 0; i < splitRelativePath.Length - 1; ++i)
            {
                folderPath = folderPath + "/" + splitRelativePath[i];
                string folderGuid = AssetDatabase.AssetPathToGUID(folderPath);
                if (!AddressableAssetUtility.IsPathValidForEntry(folderPath))
                {
                    return(null);
                }
                var folderEntry = settings.CreateSubEntryIfUnique(folderGuid, address + "/" + folderPath.Remove(assetPath.Length), this);
                if (folderEntry != null)
                {
                    folderEntry.IsInResources = IsInResources;
                    folderEntry.m_Labels      = m_Labels;
                    folderEntry.IsFolder      = true;
                }
                else
                {
                    return(null);
                }
            }

            assetEntry = settings.CreateSubEntryIfUnique(subAssetGuid, address + relativePath, this);
            if (assetEntry == null || assetEntry.IsSubAsset == false)
            {
                return(null);
            }
            return(assetEntry);
        }
 /// <summary>
 /// Set Addressables Key/ID of an object.
 /// </summary>
 /// <param name="o">Object to set Key/ID</param>
 /// <param name="id">Key/ID</param>
 public static void SetAddressableID(this Object o, string id)
 {
     if (id.Length == 0)
     {
         Debug.LogWarning($"Can not set an empty adressables ID.");
     }
     UnityEditor.AddressableAssets.Settings.AddressableAssetEntry entry = GetAddressableAssetEntry(o);
     if (entry != null)
     {
         entry.address = id;
     }
 }
Example #6
0
        string GetInternalIdFromFolderEntry(string keyStr, AddressableAssetEntry entry)
        {
            var entryPath = entry.AssetPath;

            if (keyStr.StartsWith(entry.address + "/"))
            {
                return(entryPath + keyStr.Substring(entry.address.Length));
            }
            foreach (var l in entry.labels)
            {
                if (keyStr.StartsWith(l + "/"))
                {
                    return(entryPath + keyStr.Substring(l.Length));
                }
            }
            return(string.Empty);
        }
Example #7
0
        static void GatherEntryLocations(AddressableAssetEntry entry, Type type, IList <IResourceLocation> locations, AddressableAssetTree assetTree)
        {
            if (!string.IsNullOrEmpty(entry.address) && entry.address.Contains("[") && entry.address.Contains("]"))
            {
                Debug.LogErrorFormat("Address '{0}' cannot contain '[ ]'.", entry.address);
                return;
            }
            using (new AddressablesFileEnumerationScope(assetTree))
            {
                entry.GatherAllAssets(null, true, true, false, e =>
                {
                    if (e.IsScene)
                    {
                        if (type == null || type == typeof(SceneInstance) || AddressableAssetUtility.MapEditorTypeToRuntimeType(e.MainAssetType, false) == type)
                        {
                            locations.Add(new ResourceLocationBase(e.address, e.AssetPath, typeof(SceneProvider).FullName, typeof(SceneInstance)));
                        }
                    }
                    else if (type == null || type.IsAssignableFrom(e.MainAssetType))
                    {
                        locations.Add(new ResourceLocationBase(e.address, e.AssetPath, typeof(AssetDatabaseProvider).FullName, e.MainAssetType));
                        return(true);
                    }
                    else
                    {
                        ObjectIdentifier[] ids = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(new GUID(e.guid), EditorUserBuildSettings.activeBuildTarget);
                        if (ids.Length > 1)
                        {
                            foreach (var t in AddressableAssetEntry.GatherSubObjectTypes(ids, e.guid))
                            {
                                if (type.IsAssignableFrom(t))
                                {
                                    locations.Add(new ResourceLocationBase(e.address, e.AssetPath, typeof(AssetDatabaseProvider).FullName, t));
                                }
                            }

                            return(true);
                        }
                    }
                    return(false);
                });
            }
        }
Example #8
0
        /// <summary>
        /// Gathers all asset entries.  Each explicit entry may contain multiple sub entries. For example, addressable folders create entries for each asset contained within.
        /// </summary>
        /// <param name="assets">The generated list of entries.  For simple entries, this will contain just the entry itself if specified.</param>
        /// <param name="includeSelf">Determines if the entry should be contained in the result list or just sub entries.</param>
        /// <param name="recurseAll">Determines if full recursion should be done when gathering entries.</param>
        /// <param name="includeSubObjects">Determines if sub objects such as sprites should be included.</param>
        /// <param name="entryFilter">Optional predicate to run against each entry, only returning those that pass.  A null filter will return all entries</param>
        public void GatherAllAssets(List <AddressableAssetEntry> assets, bool includeSelf, bool recurseAll, bool includeSubObjects, Func <AddressableAssetEntry, bool> entryFilter = null)
        {
            var settings = parentGroup.Settings;

            if (guid == EditorSceneListName)
            {
                foreach (var s in BuiltinSceneCache.scenes)
                {
                    if (s.enabled)
                    {
                        var entry = settings.CreateSubEntryIfUnique(s.guid.ToString(), Path.GetFileNameWithoutExtension(s.path), this);
                        if (entry != null) //TODO - it's probably really bad if this is ever null. need some error detection
                        {
                            entry.IsInSceneList = true;
                            entry.m_Labels      = m_Labels;
                            if (entryFilter == null || entryFilter(entry))
                            {
                                assets.Add(entry);
                            }
                        }
                    }
                }
            }
            else if (guid == ResourcesName)
            {
                foreach (var resourcesDir in Directory.GetDirectories("Assets", "Resources", SearchOption.AllDirectories))
                {
                    foreach (var file in Directory.GetFiles(resourcesDir, "*.*", recurseAll ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                    {
                        if (AddressableAssetUtility.IsPathValidForEntry(file))
                        {
                            var g     = AssetDatabase.AssetPathToGUID(file);
                            var addr  = GetResourcesPath(file);
                            var entry = settings.CreateSubEntryIfUnique(g, addr, this);
                            if (entry != null) //TODO - it's probably really bad if this is ever null. need some error detection
                            {
                                entry.IsInResources = true;
                                entry.m_Labels      = m_Labels;
                                if (entryFilter == null || entryFilter(entry))
                                {
                                    assets.Add(entry);
                                }
                            }
                        }
                    }
                    if (!recurseAll)
                    {
                        foreach (var folder in Directory.GetDirectories(resourcesDir))
                        {
                            if (AssetDatabase.IsValidFolder(folder))
                            {
                                var entry = settings.CreateSubEntryIfUnique(AssetDatabase.AssetPathToGUID(folder), GetResourcesPath(folder), this);
                                if (entry != null) //TODO - it's probably really bad if this is ever null. need some error detection
                                {
                                    entry.IsInResources = true;
                                    entry.m_Labels      = m_Labels;
                                    if (entryFilter == null || entryFilter(entry))
                                    {
                                        assets.Add(entry);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                var path = AssetPath;
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }

                if (AssetDatabase.IsValidFolder(path))
                {
                    foreach (var fi in Directory.GetFiles(path, "*.*", recurseAll ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                    {
                        var file = fi.Replace('\\', '/');
                        if (AddressableAssetUtility.IsPathValidForEntry(file))
                        {
                            var subGuid = AssetDatabase.AssetPathToGUID(file);
                            if (!BuiltinSceneCache.Contains(new GUID(subGuid)))
                            {
                                var entry = settings.CreateSubEntryIfUnique(subGuid, address + GetRelativePath(file, path), this);
                                if (entry != null)
                                {
                                    entry.IsInResources = IsInResources; //if this is a sub-folder of Resources, copy it on down
                                    entry.m_Labels      = m_Labels;
                                    if (entryFilter == null || entryFilter(entry))
                                    {
                                        assets.Add(entry);
                                    }
                                }
                            }
                        }
                    }
                    if (!recurseAll)
                    {
                        foreach (var fo in Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly))
                        {
                            var folder = fo.Replace('\\', '/');
                            if (AssetDatabase.IsValidFolder(folder))
                            {
                                var entry = settings.CreateSubEntryIfUnique(AssetDatabase.AssetPathToGUID(folder), address + GetRelativePath(folder, path), this);
                                if (entry != null)
                                {
                                    entry.IsInResources = IsInResources; //if this is a sub-folder of Resources, copy it on down
                                    entry.m_Labels      = m_Labels;
                                    if (entryFilter == null || entryFilter(entry))
                                    {
                                        assets.Add(entry);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (MainAssetType == typeof(AddressableAssetEntryCollection))
                    {
                        var col = AssetDatabase.LoadAssetAtPath <AddressableAssetEntryCollection>(AssetPath);
                        if (col != null)
                        {
                            foreach (var e in col.Entries)
                            {
                                var entry = settings.CreateSubEntryIfUnique(e.guid, e.address, this);
                                if (entry != null)
                                {
                                    entry.IsInResources = e.IsInResources;
                                    foreach (var l in e.labels)
                                    {
                                        entry.SetLabel(l, true, false);
                                    }
                                    foreach (var l in m_Labels)
                                    {
                                        entry.SetLabel(l, true, false);
                                    }
                                    if (entryFilter == null || entryFilter(entry))
                                    {
                                        assets.Add(entry);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (includeSelf)
                        {
                            if (entryFilter == null || entryFilter(this))
                            {
                                assets.Add(this);
                            }
                        }
                        if (includeSubObjects)
                        {
                            var mainType = AssetDatabase.GetMainAssetTypeAtPath(AssetPath);
                            if (mainType == typeof(SpriteAtlas))
                            {
                                var atlas   = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(AssetPath);
                                var sprites = new Sprite[atlas.spriteCount];
                                atlas.GetSprites(sprites);

                                for (int i = 0; i < atlas.spriteCount; i++)
                                {
                                    var spriteName = sprites[i].name;
                                    if (spriteName.EndsWith("(Clone)"))
                                    {
                                        spriteName = spriteName.Replace("(Clone)", "");
                                    }

                                    var namedAddress = string.Format("{0}[{1}]", address, spriteName);
                                    var newEntry     = new AddressableAssetEntry("", namedAddress, parentGroup, true);
                                    newEntry.IsSubAsset    = true;
                                    newEntry.ParentEntry   = this;
                                    newEntry.IsInResources = IsInResources;
                                    assets.Add(newEntry);
                                }
                            }
                            var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetPath);
                            for (int i = 0; i < objs.Length; i++)
                            {
                                var o            = objs[i];
                                var t            = o.GetType();
                                var namedAddress = string.Format("{0}[{1}]", address, o.name);
                                var newEntry     = new AddressableAssetEntry("", namedAddress, parentGroup, true);
                                newEntry.IsSubAsset    = true;
                                newEntry.ParentEntry   = this;
                                newEntry.IsInResources = IsInResources;
                                assets.Add(newEntry);
                            }
                        }
                    }
                }
            }
        }
Example #9
0
        public bool Locate(object key, Type type, out IList <IResourceLocation> locations)
        {
            CacheKey cacheKey = new CacheKey()
            {
                m_key = key, m_type = type
            };

            if (m_Cache.TryGetValue(cacheKey, out locations))
            {
                return(locations != null);
            }

            locations = new List <IResourceLocation>();
            if (m_keyToEntries.TryGetValue(key, out HashSet <AddressableAssetEntry> entries))
            {
                foreach (AddressableAssetEntry e in entries)
                {
                    if (AssetDatabase.IsValidFolder(e.AssetPath) && !e.labels.Contains(key as string))
                    {
                        continue;
                    }

                    if (type == null)
                    {
                        if (e.MainAssetType != typeof(SceneAsset))
                        {
                            ObjectIdentifier[] ids =
                                ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(new GUID(e.guid),
                                                                                        EditorUserBuildSettings.activeBuildTarget);
                            IEnumerable <Type> subObjectTypes = AddressableAssetEntry.GatherSubObjectTypes(ids, e.guid);

                            if (subObjectTypes.Any())
                            {
                                foreach (Type t in subObjectTypes)
                                {
                                    GatherEntryLocations(e, t, locations, m_AddressableAssetTree);
                                }
                            }
                            else
                            {
                                GatherEntryLocations(e, null, locations, m_AddressableAssetTree);
                            }
                        }
                        else
                        {
                            GatherEntryLocations(e, null, locations, m_AddressableAssetTree);
                        }
                    }
                    else
                    {
                        GatherEntryLocations(e, type, locations, m_AddressableAssetTree);
                    }
                }
            }

            if (type == null)
            {
                type = typeof(UnityEngine.Object);
            }

            string keyStr = key as string;

            if (!string.IsNullOrEmpty(keyStr))
            {
                //check if the key is a guid first
                var keyPath = AssetDatabase.GUIDToAssetPath(keyStr);
                if (!string.IsNullOrEmpty(keyPath))
                {
                    //only look for folders from GUID if no locations have been found
                    if (locations.Count == 0)
                    {
                        var slash = keyPath.LastIndexOf('/');
                        while (slash > 0)
                        {
                            keyPath = keyPath.Substring(0, slash);
                            var parentFolderKey = AssetDatabase.AssetPathToGUID(keyPath);
                            if (string.IsNullOrEmpty(parentFolderKey))
                            {
                                break;
                            }

                            if (m_keyToEntries.ContainsKey(parentFolderKey))
                            {
                                AddLocations(locations, type, keyPath, AssetDatabase.GUIDToAssetPath(keyStr));
                                break;
                            }
                            slash = keyPath.LastIndexOf('/');
                        }
                    }
                }
                else
                {
                    //if the key is not a GUID, see if it is contained in a folder entry
                    keyPath = keyStr;
                    int slash = keyPath.LastIndexOf('/');
                    while (slash > 0)
                    {
                        keyPath = keyPath.Substring(0, slash);
                        if (m_keyToEntries.TryGetValue(keyPath, out var entry))
                        {
                            foreach (var e in entry)
                            {
                                AddLocations(locations, type, keyStr, GetInternalIdFromFolderEntry(keyStr, e));
                            }
                            break;
                        }
                        slash = keyPath.LastIndexOf('/');
                    }
                }

                //check resources folders
                if (m_includeResourcesFolders)
                {
                    string             resPath = keyStr;
                    UnityEngine.Object obj     = Resources.Load(resPath, type);
                    if (obj == null && keyStr.Length == 32)
                    {
                        resPath = AssetDatabase.GUIDToAssetPath(keyStr);
                        if (!string.IsNullOrEmpty(resPath))
                        {
                            int index = resPath.IndexOf("Resources/", StringComparison.Ordinal);
                            if (index >= 0)
                            {
                                int start  = index + 10;
                                int length = resPath.Length - (start + System.IO.Path.GetExtension(resPath).Length);
                                resPath = resPath.Substring(index + 10, length);
                                obj     = Resources.Load(resPath, type);
                            }
                        }
                    }
                    if (obj != null)
                    {
                        locations.Add(new ResourceLocationBase(keyStr, resPath, typeof(LegacyResourcesProvider).FullName, type));
                    }
                }
            }

            if (locations.Count == 0)
            {
                locations = null;
                m_Cache.Add(cacheKey, locations);
                return(false);
            }

            m_Cache.Add(cacheKey, locations);
            return(true);
        }
Example #10
0
 static void AddEntriesToTables(Dictionary <object, HashSet <AddressableAssetEntry> > keyToEntries, AddressableAssetEntry e)
 {
     AddEntry(e, e.address, keyToEntries);
     AddEntry(e, e.guid, keyToEntries);
     if (e.IsScene && e.IsInSceneList)
     {
         int index = BuiltinSceneCache.GetSceneIndex(new GUID(e.guid));
         if (index != -1)
         {
             AddEntry(e, index, keyToEntries);
         }
     }
     if (e.labels != null)
     {
         foreach (string l in e.labels)
         {
             AddEntry(e, l, keyToEntries);
         }
     }
 }
Example #11
0
    private static void RunAllCheckersTask()
    {
        ThreadPars[] threadParses = new ThreadPars[ThreadCount];
        for (int index = 0; index < ThreadCount; index++)
        {
            threadParses[index] = new ThreadPars();
        }

        var guids  = AssetDatabase.FindAssets("t:AddressableDispatcherConfig", new string[] { AddressableInspectorUtils.DatabaseRoot });
        var length = guids.Length;
        var count  = 0;

        foreach (var guid in guids)
        {
            count++;
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            var config    = AssetDatabase.LoadAssetAtPath <AddressableDispatcherConfig>(assetPath);
            config.Load();

            int index = count % ThreadCount;
            threadParses[index].ChildDataList.Add(config);
            threadParses[index].is_atlas_model = EditorUserSettings.GetConfigValue(AddressableTools.is_atlas_model);
        }

        List <Task <Dictionary <string, List <string> > > > taskList = new List <Task <Dictionary <string, List <string> > > >();

        taskList.Add(new Task <Dictionary <string, List <string> > >(() =>
        {
            return(ThreadFind(threadParses[0]));
        }));
        taskList[0].Start();

        taskList.Add(new Task <Dictionary <string, List <string> > >(() =>
        {
            return(ThreadFind(threadParses[1]));
        }));
        taskList[1].Start();

        taskList.Add(new Task <Dictionary <string, List <string> > >(() =>
        {
            return(ThreadFind(threadParses[2]));
        }));
        taskList[2].Start();

        taskList.Add(new Task <Dictionary <string, List <string> > >(() =>
        {
            return(ThreadFind(threadParses[3]));
        }));
        taskList[3].Start();

        for (int i = 0; i < ThreadCount; i++)
        {
            taskList[i].Wait();
        }

        //Logger.LogError("=======over=========");
        Dictionary <string, UnityEditor.AddressableAssets.Settings.AddressableAssetGroup> groupsDic = new Dictionary <string, UnityEditor.AddressableAssets.Settings.AddressableAssetGroup>();

        for (int i = 0; i < ThreadCount; i++)
        {
            foreach (var keyvalue in taskList[i].Result)
            {
                keyvalue.Value.Sort();
                foreach (var pathStr in keyvalue.Value)
                {
                    //Logger.LogError("path:" + pathStr + " groupName:" + keyvalue.Key);
                    if (!groupsDic.ContainsKey(keyvalue.Key))
                    {
                        groupsDic.Add(keyvalue.Key, AASUtility.CreateGroup(keyvalue.Key));
                    }


                    UnityEditor.AddressableAssets.Settings.AddressableAssetEntry temp_entry = null;
                    var s = AASUtility.GetSettings();
                    foreach (UnityEditor.AddressableAssets.Settings.AddressableAssetGroup group in s.groups)
                    {
                        if (group == null)
                        {
                            continue;
                        }
                        foreach (UnityEditor.AddressableAssets.Settings.AddressableAssetEntry entry in group.entries)
                        {
                            //Logger.LogError("entry.AssetPath:" + entry.AssetPath + " pathstr:" + pathStr + " group.name:" + group.name + " keyvalue.key:" + keyvalue.Key);
                            if ((entry.AssetPath.Replace('\\', '/') == pathStr.Replace('\\', '/')) && (group.name == keyvalue.Key))
                            {
                                //Logger.LogError("============temp_entry=====================" + pathStr);
                                temp_entry = entry;
                            }
                        }
                    }

                    if (temp_entry == null)
                    {
                        //Logger.LogError("=================================" + pathStr);
                        var guid = AssetDatabase.AssetPathToGUID(pathStr);
                        AASUtility.AddAssetToGroup(guid, keyvalue.Key);
                    }
                }
            }
        }

        AssetDatabase.Refresh();
    }