public void IsPathValidBlocksCommonStrings()
 {
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry(string.Empty));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry(CommonStrings.UnityEditorResourcePath));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry(CommonStrings.UnityDefaultResourcePath));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry(CommonStrings.UnityBuiltInExtraPath));
 }
Пример #2
0
 public void IsPathValidBlocksBadExtensions()
 {
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Assets/file.cs"));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Assets/file.js"));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Assets/file.boo"));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Assets/file.exe"));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Assets/file.dll"));
 }
        public void GetPathAndGUIDFromTarget_FromPrefabAsset_ReturnsCorrectPathGUIDType()
        {
            var expectedGUID = CreateTestPrefabAsset(GetAssetPath("prefab1.prefab"), "prefab1");
            var expectedPath = AssetDatabase.GUIDToAssetPath(expectedGUID);
            var obj          = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(expectedPath);

            Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry(expectedPath), $"Asset is not a valid Addressable Entry path : {expectedPath}");
            Assert.IsTrue(AddressableAssetUtility.TryGetPathAndGUIDFromTarget(obj, out var actualPath, out var actualGUID), "Could not get Path and Guid from Target at expectedPath " + expectedPath);
            Assert.AreEqual(expectedPath, actualPath);
            Assert.AreEqual(expectedGUID, actualGUID);
            AssetDatabase.DeleteAsset(expectedPath);
        }
 public void IsPathValidAllowsBasicTypes()
 {
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.asset"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.png"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.bin"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.txt"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.prefab"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.mat"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.wav"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.jpg"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.avi"));
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Assets/file.controller"));
 }
Пример #5
0
        public override List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings)
        {
            ClearAnalysis();

            if (!BuildUtility.CheckModifiedScenesAndAskToSave())
            {
                Debug.LogError("Cannot run Analyze with unsaved scenes");
                m_Results.Add(new AnalyzeResult {
                    resultName = ruleName + "Cannot run Analyze with unsaved scenes"
                });
                return(m_Results);
            }

            CalculateInputDefinitions(settings);
            var context = GetBuildContext(settings);

            RefreshBuild(context);
            ConvertBundleNamesToGroupNames(context);

            m_Results = (from bundleBuild in m_AllBundleInputDefs
                         let bundleName = bundleBuild.assetBundleName
                                          from asset in bundleBuild.assetNames
                                          select new AnalyzeResult {
                resultName = bundleName + kDelimiter + "Explicit" + kDelimiter + asset
            }).ToList();

            if (m_ExtractData.WriteData != null)
            {
                m_Results.AddRange((from fileToBundle in m_ExtractData.WriteData.FileToBundle
                                    from guid in GetImplicitGuidsForBundle(fileToBundle.Key)
                                    let bundleName = fileToBundle.Value
                                                     let assetPath = AssetDatabase.GUIDToAssetPath(guid.ToString())
                                                                     where AddressableAssetUtility.IsPathValidForEntry(assetPath)
                                                                     select new AnalyzeResult
                {
                    resultName = bundleName + kDelimiter + "Implicit" + kDelimiter + assetPath
                }).ToList());
            }

            if (m_Results.Count == 0)
            {
                m_Results.Add(noErrors);
            }

            return(m_Results);
        }
Пример #6
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;
                        }
                    }
                }
            }
        }
 public void WhenPathIsNotPackageImportFile_IsPathValidForEntry_ReturnsTrue()
 {
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Packages/com.company.demo/folder/package.json"));
 }
 public void WhenPathIsInUnityAuthoredPackage_IsPathValidForEntry_ReturnsTrue()
 {
     Assert.IsTrue(AddressableAssetUtility.IsPathValidForEntry("Packages/com.unity.demo/file.asset"));
 }
 public void IsPathValidBlocksEditorPaths(string path)
 {
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry(path));
 }
        List <AnalyzeResult> DoFakeBuild(AddressableAssetSettings settings)
        {
            m_ImplicitAssets = new HashSet <GUID>();
            List <AnalyzeResult> emptyResult = new List <AnalyzeResult>();

            emptyResult.Add(new AnalyzeResult(ruleName + " - No issues found"));
            var context = new AddressablesDataBuilderInput(settings);
            var timer   = new Stopwatch();

            timer.Start();
            var aaSettings = context.AddressableSettings;

            //gather entries
            var locations          = new List <ContentCatalogDataEntry>();
            var allBundleInputDefs = new List <AssetBundleBuild>();
            var bundleToAssetGroup = new Dictionary <string, string>();
            var runtimeData        = new ResourceManagerRuntimeData();

            runtimeData.LogResourceManagerExceptions = aaSettings.buildSettings.LogResourceManagerExceptions;

            foreach (var assetGroup in aaSettings.groups)
            {
                var schema = assetGroup.GetSchema <BundledAssetGroupSchema>();
                if (schema == null)
                {
                    continue;
                }

                var bundleInputDefs = new List <AssetBundleBuild>();
                BuildScriptPackedMode.PrepGroupBundlePacking(assetGroup, bundleInputDefs, locations, schema.BundleMode);
                for (int i = 0; i < bundleInputDefs.Count; i++)
                {
                    if (bundleToAssetGroup.ContainsKey(bundleInputDefs[i].assetBundleName))
                    {
                        var bid     = bundleInputDefs[i];
                        int count   = 1;
                        var newName = bid.assetBundleName;
                        while (bundleToAssetGroup.ContainsKey(newName) && count < 1000)
                        {
                            newName = bid.assetBundleName.Replace(".bundle", string.Format("{0}.bundle", count++));
                        }
                        bundleInputDefs[i] = new AssetBundleBuild {
                            assetBundleName = newName, addressableNames = bid.addressableNames, assetBundleVariant = bid.assetBundleVariant, assetNames = bid.assetNames
                        };
                    }

                    bundleToAssetGroup.Add(bundleInputDefs[i].assetBundleName, assetGroup.Guid);
                }
                allBundleInputDefs.AddRange(bundleInputDefs);
            }
            ExtractDataTask extractData = new ExtractDataTask();

            if (allBundleInputDefs.Count > 0)
            {
                if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                {
                    Debug.LogError("Cannot run Analyze with unsaved scenes");
                    return(emptyResult);
                }

                var buildTarget             = context.Target;
                var buildTargetGroup        = context.TargetGroup;
                var buildParams             = new AddressableAssetsBundleBuildParameters(aaSettings, bundleToAssetGroup, buildTarget, buildTargetGroup, aaSettings.buildSettings.bundleBuildPath);
                var builtinShaderBundleName = aaSettings.DefaultGroup.Name.ToLower().Replace(" ", "").Replace('\\', '/').Replace("//", "/") + "_unitybuiltinshaders.bundle";
                var buildTasks = RuntimeDataBuildTasks(builtinShaderBundleName);
                buildTasks.Add(extractData);

                var aaContext = new AddressableAssetsBuildContext
                {
                    settings           = aaSettings,
                    runtimeData        = runtimeData,
                    bundleToAssetGroup = bundleToAssetGroup,
                    locations          = locations
                };

                IBundleBuildResults buildResults;
                var exitCode = ContentPipeline.BuildAssetBundles(buildParams, new BundleBuildContent(allBundleInputDefs), out buildResults, buildTasks, aaContext);
                GenerateLocationListsTask.Run(aaContext, extractData.WriteData);
                if (exitCode < ReturnCode.Success)
                {
                    Debug.LogError("Analyze build failed. " + exitCode);
                    return(emptyResult);
                }

                HashSet <GUID> explicitGuids = new HashSet <GUID>();
                foreach (var atf in extractData.WriteData.AssetToFiles)
                {
                    explicitGuids.Add(atf.Key);
                }

                Dictionary <GUID, List <string> > implicitGuids = new Dictionary <GUID, List <string> >();
                foreach (var fto in extractData.WriteData.FileToObjects)
                {
                    foreach (ObjectIdentifier g in fto.Value)
                    {
                        if (!explicitGuids.Contains(g.guid))
                        {
                            if (!implicitGuids.ContainsKey(g.guid))
                            {
                                implicitGuids.Add(g.guid, new List <string>());
                            }
                            implicitGuids[g.guid].Add(fto.Key);
                        }
                    }
                }

                //dictionary<group, dictionary<bundle, implicit assets >>
                Dictionary <string, Dictionary <string, List <string> > > allIssues = new Dictionary <string, Dictionary <string, List <string> > >();
                foreach (var g in implicitGuids)
                {
                    if (g.Value.Count > 1) //it's duplicated...
                    {
                        var path = AssetDatabase.GUIDToAssetPath(g.Key.ToString());
                        if (!AddressableAssetUtility.IsPathValidForEntry(path) ||
                            path.ToLower().Contains("/resources/") ||
                            path.ToLower().StartsWith("resources/"))
                        {
                            continue;
                        }

                        foreach (var file in g.Value)
                        {
                            var    bun = extractData.WriteData.FileToBundle[file];
                            string groupGuid;
                            if (aaContext.bundleToAssetGroup.TryGetValue(bun, out groupGuid))
                            {
                                var group = aaSettings.FindGroup(grp => grp.Guid == groupGuid);
                                if (group != null)
                                {
                                    Dictionary <string, List <string> > groupData;
                                    if (!allIssues.TryGetValue(group.Name, out groupData))
                                    {
                                        groupData = new Dictionary <string, List <string> >();
                                        allIssues.Add(group.Name, groupData);
                                    }

                                    List <string> assets;
                                    if (!groupData.TryGetValue(bun, out assets))
                                    {
                                        assets = new List <string>();
                                        groupData.Add(bun, assets);
                                    }
                                    assets.Add(path);

                                    m_ImplicitAssets.Add(g.Key);
                                }
                            }
                        }
                    }
                }

                List <AnalyzeResult> result = new List <AnalyzeResult>();
                foreach (var group in allIssues)
                {
                    foreach (var bundle in group.Value)
                    {
                        foreach (var item in bundle.Value)
                        {
                            var issueName = ruleName + kDelimiter + group.Key + kDelimiter + bundle.Key + kDelimiter + item;
                            result.Add(new AnalyzeResult(issueName, MessageType.Warning));
                        }
                    }
                }

                if (result.Count > 0)
                {
                    return(result);
                }
            }
            return(emptyResult);
        }
Пример #11
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();
        }
Пример #12
0
 public void WhenPathIsPackageImportFile_IsPathValidForEntry_ReturnsFalse()
 {
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Packages/com.company.demo/package.json"));
     Assert.IsFalse(AddressableAssetUtility.IsPathValidForEntry("Packages/com.company.demo/package.asmdef"));
 }
        DragAndDropVisualMode HandleDragAndDropPaths(AssetEntryTreeViewItem target, DragAndDropArgs args)
        {
            DragAndDropVisualMode visualMode = DragAndDropVisualMode.None;
            
            if (target == null)
                return DragAndDropVisualMode.Rejected;

            foreach (String path in DragAndDrop.paths)
            {
                if (!AddressableAssetUtility.IsPathValidForEntry(path))
                    return DragAndDropVisualMode.Rejected;
            }
            visualMode = DragAndDropVisualMode.Copy;

            if (args.performDrop && visualMode != DragAndDropVisualMode.Rejected)
            {
                AddressableAssetGroup parent = null;
                bool targetIsGroup = false;
                if (target.group != null)
                {
                    parent = target.group;
                    targetIsGroup = true;
                }
                else if (target.entry != null)
                    parent = target.entry.parentGroup;

                if (parent != null)
                {
                    var resourcePaths = new List<string>();
                    var nonResourcePaths = new List<string>();
                    foreach (var p in DragAndDrop.paths)
                    {
                        if (AddressableAssetUtility.IsInResources(p))
                            resourcePaths.Add(p);
                        else
                            nonResourcePaths.Add(p);
                    }
                    bool canMarkNonResources = true;
                    if (resourcePaths.Count > 0)
                    {
                        canMarkNonResources = AddressableAssetUtility.SafeMoveResourcesToGroup(m_Editor.settings, parent, resourcePaths);
                    }
                    if (canMarkNonResources)
                    {
                        var entries = new List<AddressableAssetEntry>();
                        var modifiedGroups = new HashSet<AddressableAssetGroup>();
                        foreach (var p in nonResourcePaths)
                        {
                            var e = m_Editor.settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(p), parent, false, false);
                            entries.Add(e);
                            modifiedGroups.Add(e.parentGroup);
                        }
                        foreach (var g in modifiedGroups)
                            g.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, entries, false, true);
                        m_Editor.settings.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, entries, true, false);

                        if (targetIsGroup)
                        {
                            SetExpanded(target.id, true);
                        }
                    }
                }
            }

            return visualMode;
        }
        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;
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #15
0
 protected bool IsValidPath(string path)
 {
     return(AddressableAssetUtility.IsPathValidForEntry(path) &&
            !path.ToLower().Contains("/resources/") &&
            !path.ToLower().StartsWith("resources/"));
 }
Пример #16
0
        protected override DragAndDropVisualMode HandleDragAndDrop(DragAndDropArgs args)
        {
            DragAndDropVisualMode visualMode = DragAndDropVisualMode.None;

            var target = args.parentItem as AssetEntryTreeViewItem;

            if (target == null)
            {
                return(DragAndDropVisualMode.None);
            }

            if (target.entry != null && target.entry.ReadOnly)
            {
                return(DragAndDropVisualMode.None);
            }

            if (target.group != null && target.group.ReadOnly)
            {
                return(DragAndDropVisualMode.None);
            }


            if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
            {
                if (!AddressableAssetUtility.IsPathValidForEntry(DragAndDrop.paths[0]))
                {
                    visualMode = DragAndDropVisualMode.Rejected;
                }
                else
                {
                    visualMode = DragAndDropVisualMode.Copy;
                }

                if (args.performDrop && visualMode != DragAndDropVisualMode.Rejected)
                {
                    AddressableAssetGroup parent = null;
                    if (target.group != null)
                    {
                        parent = target.group;
                    }
                    else if (target.entry != null)
                    {
                        parent = target.entry.parentGroup;
                    }

                    if (parent != null)
                    {
                        var resourcePaths    = new List <string>();
                        var nonResourcePaths = new List <string>();
                        foreach (var p in DragAndDrop.paths)
                        {
                            if (AddressableAssetUtility.IsInResources(p))
                            {
                                resourcePaths.Add(p);
                            }
                            else
                            {
                                nonResourcePaths.Add(p);
                            }
                        }
                        bool canMarkNonResources = true;
                        if (resourcePaths.Count > 0)
                        {
                            canMarkNonResources = AddressableAssetUtility.SafeMoveResourcesToGroup(m_Editor.settings, parent, resourcePaths);
                        }
                        if (canMarkNonResources)
                        {
                            var entries = new List <AddressableAssetEntry>();
                            foreach (var p in nonResourcePaths)
                            {
                                entries.Add(m_Editor.settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(p), parent, false, false));
                            }
                            m_Editor.settings.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, entries, true);
                        }
                    }
                }
            }
            else
            {
                var draggedNodes = DragAndDrop.GetGenericData("AssetEntryTreeViewItem") as List <AssetEntryTreeViewItem>;
                if (draggedNodes != null && draggedNodes.Count > 0)
                {
                    visualMode = DragAndDropVisualMode.Copy;
                    if (args.performDrop)
                    {
                        AddressableAssetGroup parent = null;
                        if (target.group != null)
                        {
                            parent = target.group;
                        }
                        else if (target.entry != null)
                        {
                            parent = target.entry.parentGroup;
                        }

                        if (parent != null)
                        {
                            if (draggedNodes.First().entry.IsInResources)
                            {
                                SafeMoveResourcesToGroup(parent, draggedNodes);
                            }
                            else
                            {
                                var entries = new List <AddressableAssetEntry>();
                                foreach (var node in draggedNodes)
                                {
                                    entries.Add(m_Editor.settings.CreateOrMoveEntry(node.entry.guid, parent, false, false));
                                }
                                m_Editor.settings.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, entries, true);
                            }
                        }
                    }
                }
            }

            return(visualMode);
        }
Пример #17
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();
        }
Пример #18
0
        public void OnGUI()
        {
            if (AddressableAssetSettingsDefaultObject.Settings == null)
            {
                GUILayout.Space(50);
                if (GUILayout.Button("Create Addressables Settings"))
                {
                    m_GroupEditor = null;
                    AddressableAssetSettingsDefaultObject.Settings = AddressableAssetSettings.Create(AddressableAssetSettingsDefaultObject.kDefaultConfigFolder, AddressableAssetSettingsDefaultObject.kDefaultConfigAssetName, true, true);
                }
                //if (GUILayout.Button("Import Addressables Settings"))
                //{
                //    m_GroupEditor = null;
                //    var path = EditorUtility.OpenFilePanel("Addressables Settings Object", AddressableAssetSettingsDefaultObject.kDefaultConfigFolder, "asset");
                //    if (!string.IsNullOrEmpty(path))
                //    {
                //        var i = path.ToLower().IndexOf("/assets/");
                //        if (i > 0)
                //        {
                //            path = path.Substring(i + 1);
                //            Addressables.LogFormat("Loading Addressables Settings from {0}", path);
                //            var obj = AssetDatabase.LoadAssetAtPath<AddressableAssetSettings>(path);
                //            if (obj != null)
                //                AddressableAssetSettingsDefaultObject.Settings = obj;
                //            else
                //                Debug.LogWarning("Unable to load asset settings from: "
                //                                 + path
                //                                 + "\nPlease ensure the location included in the project directory."
                //                );
                //        }
                //    }
                //}
                GUILayout.Space(20);
                GUILayout.BeginHorizontal();
                GUILayout.Space(50);
                UnityEngine.GUI.skin.label.wordWrap = true;
                GUILayout.Label("Click the \"Create\" button above or simply drag an asset into this window to start using Addressables.  Once you begin, the Addressables system will save some assets to your project to keep up with its data");
                GUILayout.Space(50);
                GUILayout.EndHorizontal();
                switch (Event.current.type)
                {
                case EventType.DragPerform:
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    foreach (var path in DragAndDrop.paths)
                    {
                        if (AddressableAssetUtility.IsPathValidForEntry(path))
                        {
                            var guid = AssetDatabase.AssetPathToGUID(path);
                            if (!string.IsNullOrEmpty(guid))
                            {
                                if (AddressableAssetSettingsDefaultObject.Settings == null)
                                {
                                    AddressableAssetSettingsDefaultObject.Settings = AddressableAssetSettings.Create(AddressableAssetSettingsDefaultObject.kDefaultConfigFolder, AddressableAssetSettingsDefaultObject.kDefaultConfigAssetName, true, true);
                                }
                                Undo.RecordObject(AddressableAssetSettingsDefaultObject.Settings, "AddressableAssetSettings");
                                AddressableAssetSettingsDefaultObject.Settings.CreateOrMoveEntry(guid, AddressableAssetSettingsDefaultObject.Settings.DefaultGroup);
                            }
                        }
                    }
                    break;

                case EventType.DragUpdated:
                case EventType.DragExited:
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    break;
                }
            }
            else
            {
                Rect contentRect = new Rect(0, 0, position.width, position.height);

                if (m_GroupEditor == null)
                {
                    m_GroupEditor = new AddressableAssetsSettingsGroupEditor(this);
                    m_GroupEditor.OnEnable();
                }
                if (m_GroupEditor.OnGUI(contentRect))
                {
                    Repaint();
                }
            }
        }
Пример #19
0
 protected bool IsValidPath(string path)
 {
     return(AddressableAssetUtility.IsPathValidForEntry(path) &&
            path.IndexOf("/resources/", StringComparison.OrdinalIgnoreCase) < 0 &&
            !path.StartsWith("resources/", StringComparison.OrdinalIgnoreCase));
 }