コード例 #1
0
        protected override void RenameEnded(RenameEndedArgs args)
        {
            var item = FindItemInVisibleRows(args.itemID);

            if (item != null)
            {
                item.isRenaming = false;
            }

            if (args.originalName == args.newName)
            {
                return;
            }

            if (item != null)
            {
                if (item.entry != null)
                {
                    item.entry.address = args.newName;
                }
                else if (item.group != null)
                {
                    if (m_Editor.settings.IsNotUniqueGroupName(args.newName))
                    {
                        args.acceptedRename = false;
                        Addressables.LogWarning("There is already a group named '" + args.newName + "'.  Cannot rename this group to match");
                    }
                    else
                    {
                        item.group.Name = args.newName;
                    }
                }
                Reload();
            }
        }
        void CreateOrEditGradleFile(string androidPackDir, string assetPackName, DeliveryType deliveryType)
        {
            if (deliveryType == DeliveryType.None)
            {
                Addressables.Log($"Asset pack '{assetPackName}' has its delivery type set to 'None'. " +
                                 $"No gradle file will be created for this asset pack. Unity assumes that any custom asset packs with no gradle file use on-demand delivery.");
                return;
            }

            // Warn about other gradle files in the .androidpack directory
            List <string> gradleFiles = Directory.EnumerateFiles(androidPackDir, "*.gradle").Where(x => Path.GetFileName(x) != "build.gradle").ToList();

            if (gradleFiles.Count > 0)
            {
                Addressables.LogWarning($"Custom asset pack at '{androidPackDir}' contains {gradleFiles.Count} files with .gradle extension which will be ignored. " +
                                        $"Only the 'build.gradle' file will be included in the Android App Bundle.");
            }

            // Create or edit the 'build.gradle' file in the .androidpack directory
            string deliveryTypeString = CustomAssetPackUtility.DeliveryTypeToGradleString(deliveryType);
            string buildFilePath      = Path.Combine(androidPackDir, "build.gradle");
            string content            = $"apply plugin: 'com.android.asset-pack'\n\nassetPack {{\n\tpackName = \"{assetPackName}\"\n\tdynamicDelivery {{\n\t\tdeliveryType = \"{deliveryTypeString}\"\n\t}}\n}}";

            File.WriteAllText(buildFilePath, content);
        }
        internal bool LogRuntimeWarnings(string pathToBuildLogs)
        {
            if (!File.Exists(pathToBuildLogs))
            {
                return(false);
            }

            PackedPlayModeBuildLogs runtimeBuildLogs = JsonUtility.FromJson <PackedPlayModeBuildLogs>(File.ReadAllText(pathToBuildLogs));
            bool messageLogged = false;

            foreach (var log in runtimeBuildLogs.RuntimeBuildLogs)
            {
                messageLogged = true;
                switch (log.Type)
                {
                case LogType.Warning:
                    Addressables.LogWarning(log.Message);
                    break;

                case LogType.Error:
                    Addressables.LogError(log.Message);
                    break;

                case LogType.Log:
                    Addressables.Log(log.Message);
                    break;
                }
            }

            return(messageLogged);
        }
        bool HasRequiredSchemas(AddressableAssetSettings settings, AddressableAssetGroup group)
        {
            bool hasBundledSchema = group.HasSchema <BundledAssetGroupSchema>();
            bool hasPADSchema     = group.HasSchema <PlayAssetDeliverySchema>();

            if (!hasBundledSchema && !hasPADSchema)
            {
                return(false);
            }
            if (!hasBundledSchema && hasPADSchema)
            {
                Addressables.LogWarning($"Group '{group.name}' has a '{typeof(PlayAssetDeliverySchema).Name}' but not a '{typeof(BundledAssetGroupSchema).Name}'. " +
                                        $"It does not contain any bundled content to be assigned to an asset pack.");
                return(false);
            }
            if (hasBundledSchema && !hasPADSchema)
            {
                var    bundledSchema = group.GetSchema <BundledAssetGroupSchema>();
                string buildPath     = bundledSchema.BuildPath.GetValue(settings);
                if (BuildPathIncludedInStreamingAssets(buildPath))
                {
                    Addressables.Log($"Group '{group.name}' does not have a '{typeof(PlayAssetDeliverySchema).Name}' but its build path '{buildPath}' will be included in StreamingAssets at build time. " +
                                     $"The group will be assigned to the generated asset packs unless its build path is changed.");
                }
                return(false);
            }
            return(true);
        }
コード例 #5
0
    static void CreateCatalog(AddressableAssetSettings aaSettings, ContentCatalogData contentCatalog, List <ResourceLocationData> locations, string playerVersion, string localCatalogFilename, FileRegistry registry, string localBuildPath)
    {
        //var localBuildPath = Addressables.BuildPath + "/" + localCatalogFilename;
        localBuildPath += "/" + localCatalogFilename;
        var localLoadPath = "{UnityEngine.AddressableAssets.Addressables.RuntimePath}/" + localCatalogFilename;

        var jsonText = JsonUtility.ToJson(contentCatalog);

        WriteFile(localBuildPath, jsonText, registry);

        string[] dependencyHashes = null;
        if (aaSettings.BuildRemoteCatalog)
        {
            var contentHash = HashingMethods.Calculate(jsonText).ToString();

            var versionedFileName = aaSettings.profileSettings.EvaluateString(aaSettings.activeProfileId, "/catalog_" + playerVersion);
            var remoteBuildFolder = aaSettings.RemoteCatalogBuildPath.GetValue(aaSettings);
            var remoteLoadFolder  = aaSettings.RemoteCatalogLoadPath.GetValue(aaSettings);

            if (string.IsNullOrEmpty(remoteBuildFolder) ||
                string.IsNullOrEmpty(remoteLoadFolder) ||
                remoteBuildFolder == AddressableAssetProfileSettings.undefinedEntryValue ||
                remoteLoadFolder == AddressableAssetProfileSettings.undefinedEntryValue)
            {
                Addressables.LogWarning("Remote Build and/or Load paths are not set on the main AddressableAssetSettings asset, but 'Build Remote Catalog' is true.  Cannot create remote catalog.  In the inspector for any group, double click the 'Addressable Asset Settings' object to begin inspecting it. '" + remoteBuildFolder + "', '" + remoteLoadFolder + "'");
            }
            else
            {
                var remoteJsonBuildPath = remoteBuildFolder + versionedFileName + ".json";
                var remoteHashBuildPath = remoteBuildFolder + versionedFileName + ".hash";

                WriteFile(remoteJsonBuildPath, jsonText, registry);
                WriteFile(remoteHashBuildPath, contentHash, registry);

                dependencyHashes = new string[((int)ContentCatalogProvider.DependencyHashIndex.Count)];
                dependencyHashes[(int)ContentCatalogProvider.DependencyHashIndex.Remote] = ResourceManagerRuntimeData.kCatalogAddress + "RemoteHash";
                dependencyHashes[(int)ContentCatalogProvider.DependencyHashIndex.Cache]  = ResourceManagerRuntimeData.kCatalogAddress + "CacheHash";

                var remoteHashLoadPath = remoteLoadFolder + versionedFileName + ".hash";
                locations.Add(new ResourceLocationData(
                                  new[] { dependencyHashes[(int)ContentCatalogProvider.DependencyHashIndex.Remote] },
                                  remoteHashLoadPath,
                                  typeof(TextDataProvider), typeof(string)));

                var cacheLoadPath = "{UnityEngine.Application.persistentDataPath}/com.unity.addressables" + versionedFileName + ".hash";
                locations.Add(new ResourceLocationData(
                                  new[] { dependencyHashes[(int)ContentCatalogProvider.DependencyHashIndex.Cache] },
                                  cacheLoadPath,
                                  typeof(TextDataProvider), typeof(string)));
            }
        }

        locations.Add(new ResourceLocationData(
                          new[] { ResourceManagerRuntimeData.kCatalogAddress },
                          localLoadPath,
                          typeof(ContentCatalogProvider),
                          typeof(ContentCatalogData),
                          dependencyHashes));
    }
コード例 #6
0
        private void HandleDragAndDrop(SerializedProperty property, bool isDragging, bool isDropping, string guid)
        {
            var aaSettings = AddressableAssetSettingsDefaultObject.Settings;
            //During the drag, doing a light check on asset validity.  The in-depth check happens during a drop, and should include a log if it fails.
            var rejectedDrag = false;

            if (isDragging)
            {
                if (aaSettings == null)
                {
                    rejectedDrag = true;
                }
                else
                {
                    var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                    rejectedDrag = AssetReferenceDrawerUtilities.ValidateDrag(m_AssetRefObject, Restrictions, aaEntries, DragAndDrop.objectReferences, DragAndDrop.paths);
                }
                DragAndDrop.visualMode = rejectedDrag ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Copy;
            }

            if (!rejectedDrag && isDropping)
            {
                var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                if (aaEntries != null)
                {
                    if (aaEntries.Count == 1)
                    {
                        var item = aaEntries[0];
                        if (item.entry != null)
                        {
                            if (item.entry.IsInResources)
                            {
                                Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first.");
                            }
                            else
                            {
                                if (AssetReferenceDrawerUtilities.SetObject(ref m_AssetRefObject, ref m_ReferencesSame, property, item.entry.TargetAsset, fieldInfo, m_label.text, out guid))
                                {
                                    TriggerOnValidate(property);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length == 1)
                    {
                        var path = DragAndDrop.paths[0];
                        DragAndDropNotFromAddressableGroupWindow(path, guid, property, aaSettings);
                    }
                }
            }
        }
        protected override TResult DoBuild <TResult>(AddressablesDataBuilderInput builderInput, AddressableAssetsBuildContext aaContext)
        {
            // Build AssetBundles
            TResult result = base.DoBuild <TResult>(builderInput, aaContext);

            // Don't prepare content for asset packs if the build target isn't set to Android
            if (builderInput.Target != BuildTarget.Android)
            {
                Addressables.LogWarning("Build target is not set to Android. No custom asset pack config files will be created.");
                return(result);
            }

            var resetAssetPackSchemaData = !CustomAssetPackSettings.SettingsExists;
            var customAssetPackSettings  = CustomAssetPackSettings.GetSettings(true);

            CreateCustomAssetPacks(aaContext.Settings, customAssetPackSettings, resetAssetPackSchemaData);
            return(result);
        }
コード例 #8
0
            public void Update(double diff, int bytesPerSecond)
            {
                if (m_Context == null || m_ReadFileStream == null)
                {
                    return;
                }

                int countToRead = (int)(bytesPerSecond * diff);

                try
                {
                    while (countToRead > 0)
                    {
                        int count = countToRead > m_ReadByteBuffer.Length ? m_ReadByteBuffer.Length : countToRead;
                        int read  = m_ReadFileStream.Read(m_ReadByteBuffer, 0, count);
                        m_Context.Response.OutputStream.Write(m_ReadByteBuffer, 0, read);
                        m_TotalBytesRead += read;
                        countToRead      -= count;

                        if (m_TotalBytesRead == m_ReadFileStream.Length)
                        {
                            Stop();
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    string url = m_Context.Request.Url.ToString();
                    Stop();
                    if (e.InnerException != null && e.InnerException is SocketException &&
                        e.InnerException.Message == "The socket has been shut down")
                    {
                        Addressables.LogWarning($"Connection lost: {url}. The socket has been shut down.");
                    }
                    else
                    {
                        Addressables.LogException(e);
                        throw;
                    }
                }
            }
        bool IsAssignedToCustomAssetPack(AddressableAssetSettings settings, AddressableAssetGroup group, PlayAssetDeliverySchema schema, CustomAssetPackEditorInfo assetPack)
        {
            if (!schema.IncludeInAssetPack)
            {
                var    bundledSchema = group.GetSchema <BundledAssetGroupSchema>();
                string buildPath     = bundledSchema.BuildPath.GetValue(settings);
                if (BuildPathIncludedInStreamingAssets(buildPath))
                {
                    Addressables.LogWarning($"Group '{group.name}' has 'Include In Asset Pack' disabled, but its build path '{buildPath}' will be included in StreamingAssets at build time. " +
                                            $"The group will be assigned to the streaming assets pack.");
                }
                return(false);
            }
            if (assetPack.DeliveryType == DeliveryType.InstallTime)
            {
                return(false);
            }

            return(true);
        }
コード例 #10
0
        internal void DragAndDropNotFromAddressableGroupWindow(string path, string guid, SerializedProperty property, AddressableAssetSettings aaSettings)
        {
            if (AddressableAssetUtility.IsInResources(path))
            {
                Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first. ");
            }
            else if (!AddressableAssetUtility.IsPathValidForEntry(path))
            {
                Addressables.LogWarning("Dragged asset is not valid as an Asset Reference. " + path);
            }
            else
            {
                Object obj;
                if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length == 1)
                {
                    obj = DragAndDrop.objectReferences[0];
                }
                else
                {
                    obj = AssetDatabase.LoadAssetAtPath <Object>(path);
                }

                if (AssetReferenceDrawerUtilities.SetObject(ref m_AssetRefObject, ref m_ReferencesSame, property, obj, fieldInfo, m_label.text, out guid))
                {
                    TriggerOnValidate(property);
                    aaSettings = AddressableAssetSettingsDefaultObject.GetSettings(true);
                    var entry = aaSettings.FindAssetEntry(guid);
                    if (entry == null && !string.IsNullOrEmpty(guid))
                    {
                        string assetName;
                        if (!aaSettings.IsAssetPathInAddressableDirectory(path, out assetName))
                        {
                            aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                            newGuid = guid;
                        }
                    }
                }
            }
        }
コード例 #11
0
        static void ValidateData()
        {
            if (s_Data == null)
            {
                var dataPath = Path.GetFullPath(".");
                dataPath  = dataPath.Replace("\\", "/");
                dataPath += "/Library/AddressablesConfig.dat";

                if (File.Exists(dataPath))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    try
                    {
                        using (FileStream file = new FileStream(dataPath, FileMode.Open, FileAccess.Read))
                        {
                            var data = bf.Deserialize(file) as ConfigSaveData;
                            if (data != null)
                            {
                                s_Data = data;
                            }
                        }
                    }
                    catch
                    {
                        //if the current class doesn't match what's in the file, Deserialize will throw. since this data is non-critical, we just wipe it
                        Addressables.LogWarning("Error reading Addressable Asset project config (play mode, etc.). Resetting to default.");
                        File.Delete(dataPath);
                    }
                }

                //check if some step failed.
                if (s_Data == null)
                {
                    s_Data = new ConfigSaveData();
                }
            }
        }
コード例 #12
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property == null || label == null)
            {
                Debug.LogError("Error rendering drawer for AssetReference property.");
                return;
            }
            string labelText = label.text;

            m_AssetRefObject = property.GetActualObjectForSerializedProperty <AssetReference>(fieldInfo, ref labelText);
            label.text       = labelText;
            if (m_AssetRefObject == null)
            {
                return;
            }

            EditorGUI.BeginProperty(position, label, property);

            GatherFilters(property);
            string guid       = m_AssetRefObject.AssetGUID;
            var    aaSettings = AddressableAssetSettingsDefaultObject.Settings;

            var checkToForceAddressable = string.Empty;

            if (!string.IsNullOrEmpty(newGuid) && newGuidPropertyPath == property.propertyPath)
            {
                if (newGuid == noAssetString)
                {
                    SetObject(property, null, out guid);
                    newGuid = string.Empty;
                }
                else
                {
                    if (SetObject(property, AssetDatabase.LoadAssetAtPath <Object>(AssetDatabase.GUIDToAssetPath(newGuid)), out guid))
                    {
                        checkToForceAddressable = newGuid;
                    }
                    newGuid = string.Empty;
                }
            }

            bool isNotAddressable = false;

            m_AssetName = noAssetString;
            Texture2D icon = null;

            if (aaSettings != null && !string.IsNullOrEmpty(guid))
            {
                var entry = aaSettings.FindAssetEntry(guid);
                if (entry != null)
                {
                    m_AssetName = entry.address;
                    icon        = AssetDatabase.GetCachedIcon(entry.AssetPath) as Texture2D;
                }
                else
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    if (!string.IsNullOrEmpty(path))
                    {
                        var  dir       = Path.GetDirectoryName(path);
                        bool foundAddr = false;
                        while (!string.IsNullOrEmpty(dir))
                        {
                            var dirEntry = aaSettings.FindAssetEntry(AssetDatabase.AssetPathToGUID(dir));
                            if (dirEntry != null)
                            {
                                foundAddr   = true;
                                m_AssetName = dirEntry.address + path.Remove(0, dir.Length);
                                break;
                            }
                            dir = Path.GetDirectoryName(dir);
                        }

                        if (!foundAddr)
                        {
                            m_AssetName = path;
                            if (!string.IsNullOrEmpty(checkToForceAddressable))
                            {
                                var newEntry = aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                                Addressables.LogFormat("Created AddressableAsset {0} in group {1}.", newEntry.address, aaSettings.DefaultGroup.Name);
                            }
                            else
                            {
                                if (!File.Exists(path))
                                {
                                    m_AssetName = "Missing File!";
                                }
                                else
                                {
                                    isNotAddressable = true;
                                }
                            }
                        }
                        icon = AssetDatabase.GetCachedIcon(path) as Texture2D;
                    }
                    else
                    {
                        m_AssetName = "Missing File!";
                    }
                }
            }

            assetDropDownRect = EditorGUI.PrefixLabel(position, label);
            var nameToUse = m_AssetName;

            if (isNotAddressable)
            {
                nameToUse = "Not Addressable - " + nameToUse;
            }
            if (m_AssetRefObject.editorAsset != null)
            {
                var subAssets = new List <Object>();
                subAssets.Add(null);
                var assetPath = AssetDatabase.GUIDToAssetPath(m_AssetRefObject.AssetGUID);
                subAssets.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath));
                var mainType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
                if (mainType == typeof(SpriteAtlas))
                {
                    var atlas   = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(assetPath);
                    var sprites = new Sprite[atlas.spriteCount];
                    atlas.GetSprites(sprites);
                    subAssets.AddRange(sprites);
                }

                if (subAssets.Count > 1)
                {
                    assetDropDownRect = new Rect(assetDropDownRect.position, new Vector2(assetDropDownRect.width / 2, assetDropDownRect.height));
                    var objRect  = new Rect(assetDropDownRect.xMax, assetDropDownRect.y, assetDropDownRect.width, assetDropDownRect.height);
                    var objNames = new string[subAssets.Count];
                    var selIndex = 0;
                    for (int i = 0; i < subAssets.Count; i++)
                    {
                        var s       = subAssets[i];
                        var objName = s == null ? "<none>" : s.name;
                        if (objName.EndsWith("(Clone)"))
                        {
                            objName = objName.Replace("(Clone)", "");
                        }
                        objNames[i] = objName;
                        if (m_AssetRefObject.SubObjectName == objName)
                        {
                            selIndex = i;
                        }
                    }
                    //TODO: handle large amounts of sprites with a custom popup
                    var newIndex = EditorGUI.Popup(objRect, selIndex, objNames);
                    if (newIndex != selIndex)
                    {
                        Undo.RecordObject(property.serializedObject.targetObject, "Assign Asset Reference Sub Object");
                        var success = m_AssetRefObject.SetEditorSubObject(subAssets[newIndex]);
                        if (success)
                        {
                            EditorUtility.SetDirty(property.serializedObject.targetObject);
                            var comp = property.serializedObject.targetObject as Component;
                            if (comp != null && comp.gameObject != null && comp.gameObject.activeInHierarchy)
                            {
                                EditorSceneManager.MarkSceneDirty(comp.gameObject.scene);
                            }
                        }
                    }
                }
            }
            if (EditorGUI.DropdownButton(assetDropDownRect, new GUIContent(nameToUse, icon, m_AssetName), FocusType.Keyboard))
            {
                newGuidPropertyPath = property.propertyPath;
                var nonAddressedOption = isNotAddressable ? m_AssetName : string.Empty;
                PopupWindow.Show(assetDropDownRect, new AssetReferencePopup(this, guid, nonAddressedOption));
            }


            //During the drag, doing a light check on asset validity.  The in-depth check happens during a drop, and should include a log if it fails.
            var rejectedDrag = false;

            if (Event.current.type == EventType.DragUpdated && position.Contains(Event.current.mousePosition))
            {
                if (aaSettings == null)
                {
                    rejectedDrag = true;
                }
                else
                {
                    var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                    if (aaEntries != null)
                    {
                        if (aaEntries.Count != 1)
                        {
                            rejectedDrag = true;
                        }
                        else
                        {
                            if (aaEntries[0] == null || aaEntries[0].entry == null || aaEntries[0].entry.IsInResources || !ValidateAsset(aaEntries[0].entry.AssetPath))
                            {
                                rejectedDrag = true;
                            }
                        }
                    }
                    else
                    {
                        if (DragAndDrop.paths.Length != 1)
                        {
                            rejectedDrag = true;
                        }
                        else
                        {
                            if (!ValidateAsset(DragAndDrop.paths[0]))
                            {
                                rejectedDrag = true;
                            }
                        }
                    }
                }
                DragAndDrop.visualMode = rejectedDrag ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Copy;
            }

            if (!rejectedDrag && Event.current.type == EventType.DragPerform && position.Contains(Event.current.mousePosition))
            {
                var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                if (aaEntries != null)
                {
                    if (aaEntries.Count == 1)
                    {
                        var item = aaEntries[0];
                        if (item.entry != null)
                        {
                            if (item.entry.IsInResources)
                            {
                                Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first.");
                            }
                            else
                            {
                                SetObject(property, item.entry.TargetAsset, out guid);
                            }
                        }
                    }
                }
                else
                {
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length == 1)
                    {
                        var path = DragAndDrop.paths[0];
                        if (AddressableAssetUtility.IsInResources(path))
                        {
                            Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first. ");
                        }
                        else if (!AddressableAssetUtility.IsPathValidForEntry(path))
                        {
                            Addressables.LogWarning("Dragged asset is not valid as an Asset Reference. " + path);
                        }
                        else
                        {
                            Object obj;
                            if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length == 1)
                            {
                                obj = DragAndDrop.objectReferences[0];
                            }
                            else
                            {
                                obj = AssetDatabase.LoadAssetAtPath <Object>(path);
                            }

                            if (SetObject(property, obj, out guid))
                            {
                                aaSettings = AddressableAssetSettingsDefaultObject.GetSettings(true);
                                var entry = aaSettings.FindAssetEntry(guid);
                                if (entry == null && !string.IsNullOrEmpty(guid))
                                {
                                    aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                                    newGuid = guid;
                                }
                            }
                        }
                    }
                }
            }

            EditorGUI.EndProperty();
        }
コード例 #13
0
    internal static List <AssetEntryRevertOperation> DetermineRequiredAssetEntryUpdates(AddressableAssetGroup group, ContentUpdateScript.ContentUpdateContext contentUpdateContext)
    {
        if (!group.HasSchema <BundledAssetGroupSchema>())
        {
            return(new List <AssetEntryRevertOperation>());
        }

        bool groupIsStaticContentGroup = group.HasSchema <ContentUpdateGroupSchema>() && group.GetSchema <ContentUpdateGroupSchema>().StaticContent;
        List <AssetEntryRevertOperation> operations = new List <AssetEntryRevertOperation>();

        foreach (AddressableAssetEntry entry in group.entries)
        {
            GUID guid = new GUID(entry.guid);
            if (!contentUpdateContext.WriteData.AssetToFiles.ContainsKey(guid))
            {
                continue;
            }

            string file = contentUpdateContext.WriteData.AssetToFiles[guid][0];
            string fullInternalBundleName = contentUpdateContext.WriteData.FileToBundle[file];
            string finalBundleWritePath   = contentUpdateContext.BundleToInternalBundleIdMap[fullInternalBundleName];

            //Ensure we can get the catalog entry for the bundle we're looking to replace
            if (!contentUpdateContext.IdToCatalogDataEntryMap.TryGetValue(finalBundleWritePath, out ContentCatalogDataEntry catalogBundleEntry))
            {
                continue;
            }

            //If new entries are added post initial build this will ensure that those new entries have their bundleFileId for SaveContentState
            entry.BundleFileId = catalogBundleEntry.InternalId;

            //If we have no cached state no reason to proceed.  This is new to the build.
            if (!contentUpdateContext.GuidToPreviousAssetStateMap.TryGetValue(entry.guid, out CachedAssetState previousAssetState))
            {
                continue;
            }

            //If the parent group is different we don't want to revert it to its previous state
            if (entry.parentGroup.Guid != previousAssetState.groupGuid)
            {
                continue;
            }

            //If the asset hash has changed and the group is not a static content update group we don't want to revert it to its previous state
            if (AssetDatabase.GetAssetDependencyHash(entry.AssetPath) != previousAssetState.asset.hash && !groupIsStaticContentGroup)
            {
                continue;
            }

            //If the previous asset state has the same bundle file id as the current build we don't want to revert it to its previous state
            if (catalogBundleEntry.InternalId == previousAssetState.bundleFileId)
            {
                continue;
            }

            var    schema    = group.GetSchema <BundledAssetGroupSchema>();
            string loadPath  = schema.LoadPath.GetValue(group.Settings);
            string buildPath = schema.BuildPath.GetValue(group.Settings);

            //Need to check and make sure our cached version exists
            if (string.IsNullOrEmpty(previousAssetState.bundleFileId))
            {
                //Logging this as an error because a CachedAssetState without a set bundleFileId is indicative of a significant issue with the build script.
                Addressables.LogError($"CachedAssetState found for {entry.AssetPath} but the bundleFileId was never set on the previous build.");
                continue;
            }

            string previousBundlePath = previousAssetState.bundleFileId?.Replace(loadPath, buildPath);

            if (!File.Exists(previousBundlePath))
            {
                //Logging this as a warning because users may choose to delete their bundles on disk which will trigger this state.
                Addressables.LogWarning($"CachedAssetState found for {entry.AssetPath} but the previous bundle at {previousBundlePath} cannot be found. " +
                                        $"The modified assets will not be able to use the previously built bundle which will result in new bundles being created " +
                                        $"for these static content groups.  This will point the Content Catalog to local bundles that do not exist on currently " +
                                        $"deployed versions of an application.");
                continue;
            }

            string builtBundlePath = contentUpdateContext.BundleToInternalBundleIdMap[fullInternalBundleName].Replace(loadPath, buildPath);

            AssetEntryRevertOperation operation = new AssetEntryRevertOperation()
            {
                BundleCatalogEntry = catalogBundleEntry,
                AssetEntry         = entry,
                CurrentBuildPath   = builtBundlePath,
                PreviousAssetState = previousAssetState,
                PreviousBuildPath  = previousBundlePath
            };

            operations.Add(operation);
        }
        return(operations);
    }
コード例 #14
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property == null || label == null)
            {
                Debug.LogError("Error rendering drawer for AssetReference property.");
                return;
            }
            string labelText = label.text;

            m_AssetRefObject = property.GetActualObjectForSerializedProperty <AssetReference>(fieldInfo, ref labelText);
            label.text       = labelText;
            if (m_AssetRefObject == null)
            {
                return;
            }

            EditorGUI.BeginProperty(position, label, property);

            GatherFilters(property);
            string guid       = m_AssetRefObject.RuntimeKey.ToString();
            var    aaSettings = AddressableAssetSettingsDefaultObject.Settings;

            var checkToForceAddressable = string.Empty;

            if (!string.IsNullOrEmpty(newGuid) && newGuidPropertyPath == property.propertyPath)
            {
                if (newGuid == noAssetString)
                {
                    SetObject(property, null, out guid);
                    newGuid = string.Empty;
                }
                else
                {
                    if (SetObject(property, AssetDatabase.LoadAssetAtPath <Object>(AssetDatabase.GUIDToAssetPath(newGuid)), out guid))
                    {
                        checkToForceAddressable = newGuid;
                    }
                    newGuid = string.Empty;
                }
            }

            bool isNotAddressable = false;

            m_AssetName = noAssetString;
            Texture2D icon = null;

            if (aaSettings != null && !string.IsNullOrEmpty(guid))
            {
                var entry = aaSettings.FindAssetEntry(guid);
                if (entry != null)
                {
                    m_AssetName = entry.address;
                    icon        = AssetDatabase.GetCachedIcon(entry.AssetPath) as Texture2D;
                }
                else
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    if (!string.IsNullOrEmpty(path))
                    {
                        var  dir       = Path.GetDirectoryName(path);
                        bool foundAddr = false;
                        while (!string.IsNullOrEmpty(dir))
                        {
                            var dirEntry = aaSettings.FindAssetEntry(AssetDatabase.AssetPathToGUID(dir));
                            if (dirEntry != null)
                            {
                                foundAddr   = true;
                                m_AssetName = dirEntry.address + path.Remove(0, dir.Length);
                                break;
                            }
                            dir = Path.GetDirectoryName(dir);
                        }

                        if (!foundAddr)
                        {
                            m_AssetName = path;
                            if (!string.IsNullOrEmpty(checkToForceAddressable))
                            {
                                var newEntry = aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                                Addressables.LogFormat("Created AddressableAsset {0} in group {1}.", newEntry.address, aaSettings.DefaultGroup.Name);
                            }
                            else
                            {
                                if (!File.Exists(path))
                                {
                                    m_AssetName = "Missing File!";
                                }
                                else
                                {
                                    isNotAddressable = true;
                                }
                            }
                        }
                        icon = AssetDatabase.GetCachedIcon(path) as Texture2D;
                    }
                    else
                    {
                        m_AssetName = "Missing File!";
                    }
                }
            }

            smallPos = EditorGUI.PrefixLabel(position, label);
            var nameToUse = m_AssetName;

            if (isNotAddressable)
            {
                nameToUse = "Not Addressable - " + nameToUse;
            }

            if (EditorGUI.DropdownButton(smallPos, new GUIContent(nameToUse, icon, m_AssetName), FocusType.Keyboard))
            {
                newGuidPropertyPath = property.propertyPath;
                var nonAddressedOption = isNotAddressable ? m_AssetName : string.Empty;
                PopupWindow.Show(smallPos, new AssetReferencePopup(this, guid, nonAddressedOption));
            }


            //During the drag, doing a light check on asset validity.  The in-depth check happens during a drop, and should include a log if it fails.
            var rejectedDrag = false;

            if (Event.current.type == EventType.DragUpdated && position.Contains(Event.current.mousePosition))
            {
                if (aaSettings == null)
                {
                    rejectedDrag = true;
                }
                else
                {
                    var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                    if (aaEntries != null)
                    {
                        if (aaEntries.Count != 1)
                        {
                            rejectedDrag = true;
                        }
                        else
                        {
                            if (aaEntries[0] != null &&
                                aaEntries[0].entry != null &&
                                aaEntries[0].entry.IsInResources)
                            {
                                rejectedDrag = true;
                            }
                        }
                    }
                    else
                    {
                        if (DragAndDrop.paths.Length != 1)
                        {
                            rejectedDrag = true;
                        }
                    }
                }
                DragAndDrop.visualMode = rejectedDrag ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Copy;
            }

            if (!rejectedDrag && Event.current.type == EventType.DragPerform && position.Contains(Event.current.mousePosition))
            {
                var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                if (aaEntries != null)
                {
                    if (aaEntries.Count == 1)
                    {
                        var item = aaEntries[0];
                        if (item.entry != null)
                        {
                            if (item.entry.IsInResources)
                            {
                                Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first.");
                            }
                            else
                            {
                                SetObject(property, AssetDatabase.LoadAssetAtPath <Object>(item.entry.AssetPath), out guid);
                            }
                        }
                    }
                }
                else
                {
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length == 1)
                    {
                        var path = DragAndDrop.paths[0];
                        if (AddressableAssetUtility.IsInResources(path))
                        {
                            Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first. ");
                        }
                        else if (!AddressableAssetUtility.IsPathValidForEntry(path))
                        {
                            Addressables.LogWarning("Dragged asset is not valid as an Asset Reference. " + path);
                        }
                        else
                        {
                            Object obj;
                            if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length == 1)
                            {
                                obj = DragAndDrop.objectReferences[0];
                            }
                            else
                            {
                                obj = AssetDatabase.LoadAssetAtPath <Object>(path);
                            }

                            if (SetObject(property, obj, out guid))
                            {
                                aaSettings = AddressableAssetSettingsDefaultObject.GetSettings(true);
                                var entry = aaSettings.FindAssetEntry(guid);
                                if (entry == null && !string.IsNullOrEmpty(guid))
                                {
                                    aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                                    newGuid = guid;
                                }
                            }
                        }
                    }
                }
            }

            EditorGUI.EndProperty();
        }
コード例 #15
0
        private void HandleDragAndDrop(SerializedProperty property, bool isDragging, bool isDropping, string guid)
        {
            var aaSettings = AddressableAssetSettingsDefaultObject.Settings;
            //During the drag, doing a light check on asset validity.  The in-depth check happens during a drop, and should include a log if it fails.
            var rejectedDrag = false;

            if (isDragging)
            {
                if (aaSettings == null)
                {
                    rejectedDrag = true;
                }
                else
                {
                    var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                    if (aaEntries != null)
                    {
                        if (aaEntries.Count != 1)
                        {
                            rejectedDrag = true;
                        }
                        else
                        {
                            if (aaEntries[0] == null || aaEntries[0].entry == null || aaEntries[0].entry.IsInResources || !ValidateAsset(aaEntries[0].entry.AssetPath))
                            {
                                rejectedDrag = true;
                            }
                        }
                    }
                    else
                    {
                        if (DragAndDrop.paths.Length != 1)
                        {
                            rejectedDrag = true;
                        }
                        else
                        {
                            if (!ValidateAsset(DragAndDrop.paths[0]))
                            {
                                rejectedDrag = true;
                            }
                        }
                    }
                }
                DragAndDrop.visualMode = rejectedDrag ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Copy;
            }

            if (!rejectedDrag && isDropping)
            {
                var aaEntries = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                if (aaEntries != null)
                {
                    if (aaEntries.Count == 1)
                    {
                        var item = aaEntries[0];
                        if (item.entry != null)
                        {
                            if (item.entry.IsInResources)
                            {
                                Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first.");
                            }
                            else
                            {
                                SetObject(property, item.entry.TargetAsset, out guid);
                            }
                        }
                    }
                }
                else
                {
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length == 1)
                    {
                        var path = DragAndDrop.paths[0];
                        if (AddressableAssetUtility.IsInResources(path))
                        {
                            Addressables.LogWarning("Cannot use an AssetReference on an asset in Resources. Move asset out of Resources first. ");
                        }
                        else if (!AddressableAssetUtility.IsPathValidForEntry(path))
                        {
                            Addressables.LogWarning("Dragged asset is not valid as an Asset Reference. " + path);
                        }
                        else
                        {
                            Object obj;
                            if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length == 1)
                            {
                                obj = DragAndDrop.objectReferences[0];
                            }
                            else
                            {
                                obj = AssetDatabase.LoadAssetAtPath <Object>(path);
                            }

                            if (SetObject(property, obj, out guid))
                            {
                                aaSettings = AddressableAssetSettingsDefaultObject.GetSettings(true);
                                var entry = aaSettings.FindAssetEntry(guid);
                                if (entry == null && !string.IsNullOrEmpty(guid))
                                {
                                    aaSettings.CreateOrMoveEntry(guid, aaSettings.DefaultGroup);
                                    newGuid = guid;
                                }
                            }
                        }
                    }
                }
            }
        }