private static IEnumerable <SearchItem> FetchShaderGraph(SearchContext context)
        {
            var userQuery     = context.searchQuery;
            var providers     = new[] { Search.SearchService.GetProvider("adb") };
            var assetProvider = Search.SearchService.GetProvider("asset");

            using (var query = Search.SearchService.CreateContext(providers, $"t:{nameof(ShaderGraphVfxAsset)} {userQuery}", context.options))
                using (var request = Search.SearchService.Request(query))
                {
                    foreach (var r in request)
                    {
                        if (r?.ToObject <ShaderGraphVfxAsset>() == null)
                        {
                            var shader    = r.ToObject <Shader>();
                            var path      = AssetDatabase.GetAssetPath(shader);
                            var subAssets = AssetDatabase.LoadAllAssetsAtPath(path);
                            var vfxShader = subAssets.SingleOrDefault(x => x is ShaderGraphVfxAsset);
                            if (vfxShader != null)
                            {
                                var gid = GlobalObjectId.GetGlobalObjectIdSlow(vfxShader);
                                path = AssetDatabase.GetAssetPath(vfxShader);
                                var item = Search.Providers.AssetProvider.CreateItem("vfxshader", context, assetProvider, gid.ToString(), path, r.score - 900, SearchDocumentFlags.Asset | SearchDocumentFlags.Nested);
                                item.label       = vfxShader.name;
                                item.description = path;
                                yield return(item);
                            }
                        }
                        else
                        {
                            yield return(r);
                        }
                    }
                }
        }
        internal void ConvertGlobalObjectIdsToSceneObjects()
        {
            activeObjects.Clear();
            var gids          = globalObjectIdSet.ToArray();
            var outputObjects = new UnityEngine.Object[gids.Length];

            GlobalObjectId.GlobalObjectIdentifiersToObjectsSlow(gids, outputObjects);
            for (var i = 0; i < outputObjects.Length; i++)
            {
                var obj = outputObjects[i];
                //Debug.Log($"GID: {gids[i]}, OBJ: {obj} -> GUID: {GlobalObjectId.GetGlobalObjectIdSlow(obj)}");
                //Sometimes invalid objects are returned. https://fogbugz.unity3d.com/f/cases/1291291/
                //This is the workaround.
                if (obj != null)
                {
                    //if(gids[i] == GlobalObjectId.GetGlobalObjectIdSlow(obj))
                    var x = gids[i];
                    var y = GlobalObjectId.GetGlobalObjectIdSlow(obj);
                    if (y.identifierType == x.identifierType && y.targetObjectId == x.targetObjectId && y.targetPrefabId == x.targetPrefabId && y.assetGUID == x.assetGUID)
                    {
                        activeObjects.Add(obj);
                    }
                }
            }
        }
        public void Remove(UnityEngine.Object obj)
        {
            activeObjects.Remove(obj);
            var gid = GlobalObjectId.GetGlobalObjectIdSlow(obj);

            globalObjectIdSet.Remove(gid);
        }
Exemple #4
0
        private void IndexSubAsset(Object subObj, string containerPath, bool checkIfDocumentExists, bool hasCustomIndexers)
        {
            var gid                 = GlobalObjectId.GetGlobalObjectIdSlow(subObj);
            var id                  = gid.ToString();
            var containerName       = Path.GetFileNameWithoutExtension(containerPath);
            var objPathName         = Utils.RemoveInvalidCharsFromPath($"{containerName}/{subObj.name}", ' ');
            var subObjDocumentIndex = AddDocument(id, objPathName, containerPath, checkIfDocumentExists, SearchDocumentFlags.Nested | SearchDocumentFlags.Asset);

            IndexTypes(subObj.GetType(), subObjDocumentIndex);
            IndexProperty(subObjDocumentIndex, "is", "nested", saveKeyword: true, exact: true);
            IndexProperty(subObjDocumentIndex, "is", "subasset", saveKeyword: true, exact: true);
            if (settings.options.dependencies)
            {
                AddProperty("ref", containerPath.ToLowerInvariant(), subObjDocumentIndex);
            }

            if (hasCustomIndexers)
            {
                IndexCustomProperties(id, subObjDocumentIndex, subObj);
            }

            if (!string.IsNullOrEmpty(subObj.name))
            {
                IndexWordComponents(subObjDocumentIndex, subObj.name);
            }
            if (settings.options.properties)
            {
                IndexObject(subObjDocumentIndex, subObj, settings.options.dependencies);
            }
        }
Exemple #5
0
        public void ClassWithGlobalObjectId_CanBeSerializedAndDeserialized()
        {
            var image = new Texture2D(1, 1);

            AssetDatabase.CreateAsset(image, kTexture2DPath);
            AssetDatabase.ImportAsset(kTexture2DPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);

            try
            {
                var src = new ClassWithGlobalObjectId
                {
                    GlobalObjectId = GlobalObjectId.GetGlobalObjectIdSlow(image),
                    Guid           = GUID.Generate()
                };

                var dst = SerializeAndDeserialize(src);

                Assert.That(dst, Is.Not.SameAs(src));
                Assert.That(dst.GlobalObjectId, Is.EqualTo(src.GlobalObjectId));
                Assert.That(dst.Guid, Is.EqualTo(src.Guid));
            }
            finally
            {
                AssetDatabase.DeleteAsset(kTexture2DPath);
            }
        }
        private static ulong GetId(Object obj)
        {
            if (obj != null)
            {
#if UNITY_2019_2_OR_NEWER
                var guid = GlobalObjectId.GetGlobalObjectIdSlow(obj);
                var id   = guid.targetObjectId;

                return(id);
#else
                var inspectorModeInfo =
                    typeof(SerializedObject).GetProperty(INSPECTOR_MODE,
                                                         BindingFlags.NonPublic | BindingFlags.Instance);

                var serializedObject = new SerializedObject(obj);
                inspectorModeInfo?.SetValue(serializedObject, InspectorMode.Debug, null);

                var
                    localIdProp = serializedObject.FindProperty(LOCAL_IDENTIFIER);

                var localId = localIdProp.longValue;
                if (localId <= 0)
                {
#if UNITY_2018_3_OR_NEWER
                    var prefabType = PrefabUtility.GetPrefabAssetType(obj);
                    if (prefabType != PrefabAssetType.NotAPrefab)
                    {
                        var prefab = PrefabUtility.GetPrefabInstanceHandle(obj);
#else
                    var prefabType = PrefabUtility.GetPrefabType(obj);
                    if (prefabType != PrefabType.None)
                    {
                        var prefab = PrefabUtility.GetPrefabParent(obj);
#endif
                        return(GetId(prefab));
                    }

                    var sceneDirty = false;
                    if (obj as GameObject != null)
                    {
                        sceneDirty = ((GameObject)obj).scene.isDirty;
                    }
                    else if ((obj as MonoBehaviour)?.gameObject != null)
                    {
                        sceneDirty = ((MonoBehaviour)obj).gameObject.scene.isDirty;
                    }

                    if (sceneDirty && localId == 0)
                    {
                        localId = obj.GetInstanceID();
                    }
                }

                return((ulong)localId);
#endif
            }

            return(0);
        }
Exemple #7
0
        public static ObjectID GetFor(Object o)
        {
            var goid     = GlobalObjectId.GetGlobalObjectIdSlow(o);
            var id       = goid.targetObjectId;
            var prefabId = goid.targetPrefabId;

            return(new ObjectID(id, prefabId));
        }
Exemple #8
0
 internal static string ExtractDataValue(object data, out ExportedType type, bool convertForCSV = false)
 {
     if (data == null)
     {
         type = ExportedType.None;
         return(string.Empty);
     }
     else if (data is UnityEngine.Object o)
     {
         type = ExportedType.ObjectReference;
         string objectToString = o.name;
         if (string.IsNullOrEmpty(o.name))
         {
             objectToString = AssetDatabase.GetAssetPath(o);
             if (string.IsNullOrEmpty(objectToString))
             {
                 objectToString = o.GetType().ToString();
             }
         }
         if (convertForCSV)
         {
             return(o.ToString());
         }
         else
         {
             return($"{GlobalObjectId.GetGlobalObjectIdSlow(o).ToString()};{objectToString}");
         }
     }
     else if (data is SerializedProperty sp)
     {
         return(ExtractDataValue(PropertySelectors.GetSerializedPropertyValue(sp), out type));
     }
     else if (data is MaterialProperty mp)
     {
         return(ExtractDataValue(MaterialSelectors.GetMaterialPropertyValue(mp), out type));
     }
     else if (data is Color color)
     {
         type = ExportedType.Color;
         return('#' + ColorUtility.ToHtmlStringRGBA(color));
     }
     else
     {
         if (data is bool)
         {
             type = ExportedType.Bool;
         }
         else if (Utils.TryGetNumber(data, out var number))
         {
             type = ExportedType.Number;
         }
         else
         {
             type = ExportedType.String;
         }
         return(data.ToString());
     }
 }
Exemple #9
0
    static string GetKey(GameObject gameObject, string label)
    {
        if (!st_current._keyDictionary.ContainsKey(gameObject))
        {
            st_current._keyDictionary.Add(gameObject, GlobalObjectId.GetGlobalObjectIdSlow(gameObject).ToString());
        }

        return($"{gameObject.name}_{label}_{st_current._keyDictionary[gameObject]}");
    }
Exemple #10
0
        public void Deserialize_PipelineAsBuildStep_IsValid()
        {
            var assetPath  = $"Assets/TestBuildPipeline{BuildPipeline.AssetExtension}";
            var pipeline   = BuildPipeline.CreateAsset(assetPath);
            var pipelineId = GlobalObjectId.GetGlobalObjectIdSlow(pipeline);

            Assert.That(BuildStep.Deserialize(pipelineId.ToString()), Is.EqualTo(pipeline));
            AssetDatabase.DeleteAsset(assetPath);
        }
        private static SceneList.SceneInfo GetSceneInfo(string path)
        {
            var sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(path);

            return(new SceneList.SceneInfo()
            {
                AutoLoad = true, Scene = GlobalObjectId.GetGlobalObjectIdSlow(sceneAsset)
            });
        }
        static string GetBuildSettingsName(BuildSettings settings)
        {
            var name = settings.name;

            if (string.IsNullOrEmpty(name))
            {
                name = GlobalObjectId.GetGlobalObjectIdSlow(settings).ToString();
            }
            return(name);
        }
        static string GetBuildConfigurationName(BuildConfiguration config)
        {
            var name = config.name;

            if (string.IsNullOrEmpty(name))
            {
                name = GlobalObjectId.GetGlobalObjectIdSlow(config).ToString();
            }
            return(name);
        }
Exemple #14
0
        internal static BuildPipelineResult DoBuild(NPath asmdef, BuildTarget buildTarget, bool runBee = true, Action <BuildContext> onBuildCompleted = null)
        {
            var relativePath = asmdef.RelativeTo(".");
            var name         = asmdef.FileNameWithoutExtension;
            var outputDir    = new DirectoryInfo("./Library/DotsRuntimeBuild");
            var stagingDir   = outputDir.Combine(name);
            var dataDir      = stagingDir.Combine("Data");

            var profile = new DotsRuntimeBuildProfile
            {
                RootAssembly  = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(relativePath.ToString()),
                Target        = buildTarget,
                Configuration = BuildConfiguration.Debug
            };

            var buildSettings = BuildSettings.CreateInstance((bs) =>
            {
                bs.hideFlags = HideFlags.HideAndDontSave;
                bs.SetComponent(profile);
                bs.SetComponent(new OutputBuildDirectory {
                    OutputDirectory = $"Library/DotsRuntimeBuild/build/Mole3D/{profile.BeeTargetName}"
                });
            });

            var convSettings = new ConversionSystemFilterSettings("Unity.Rendering.Hybrid");

            buildSettings.SetComponent(convSettings);

            var sceneList     = new SceneList();
            var rootScenePath = ConversionUtils.GetScenePathForSceneWithName(name);
            var scene         = AssetDatabase.LoadAssetAtPath <SceneAsset>(rootScenePath);

            sceneList.Scenes.Add(GlobalObjectId.GetGlobalObjectIdSlow(scene));
            buildSettings.SetComponent(sceneList);

            var buildPipeline = BuildPipeline.CreateInstance((pipeline) =>
            {
                pipeline.hideFlags = HideFlags.HideAndDontSave;
                pipeline.BuildSteps.Add(new BuildStepExportEntities());
                pipeline.BuildSteps.Add(new BuildStepExportConfiguration());
                pipeline.BuildSteps.Add(new BuildStepGenerateBeeFiles());
                if (runBee)
                {
                    pipeline.BuildSteps.Add(new BuildStepRunBee());
                }
                ;
            });

            // Run build pipeline
            using (var progress = new BuildProgress($"Build {profile.Target.DisplayName} {profile.Configuration}", "Building..."))
            {
                return(buildPipeline.Build(buildSettings, progress));
            }
        }
Exemple #15
0
        public static List <SearchItem> GetAllSearchQueryItems(SearchContext context)
        {
            s_SavedQueries = s_SavedQueries ?? GetAllQueries();
            var queryProvider = SearchService.GetProvider(Providers.Query.type);

            return(s_SavedQueries.Where(query => query && query.providerIds.Any(id => context.filters.Any(f => f.isEnabled && f.provider.name.id == id))).Select(query =>
            {
                var id = GlobalObjectId.GetGlobalObjectIdSlow(query).ToString();
                var description = string.IsNullOrEmpty(query.description) ? $"{query.searchQuery} - {AssetDatabase.GetAssetPath(query)}" : query.description;
                var thumbnail = query.icon ? query.icon : Icons.favorite;
                return queryProvider.CreateItem(context, id, query.name, description, thumbnail, query);
            }).ToList());
        }
Exemple #16
0
        public void OnProcessScene(UnityEngine.SceneManagement.Scene scene, BuildReport report)
        {
            Debug.Log("SceneProcessor.OnProcessScene " + scene.name);

            // Set the ID of all StatefulObjects in this scene, using the GlobalObjectId to ensure sort order is consistent between builds
            var objects = UnityEngine.Object.FindObjectsOfType <StatefulObject>();

            // For any future optimizations such as ensuring frequently changing StatefulObjects have lower IDs update the sort method here
            // using GlobalObjectId as a tie breaker
            Array.Sort(objects, (x, y) => GlobalObjectId.GetGlobalObjectIdSlow(x).ToString().CompareTo(GlobalObjectId.GetGlobalObjectIdSlow(y).ToString()));
            for (int i = 0; i < objects.Length; i++)
            {
                objects[i].ID = i;
            }
        }
Exemple #17
0
        internal static string Serialize(IBuildStep step)
        {
            if (step == null)
            {
                return(null);
            }

            if (step is BuildPipeline pipeline)
            {
                return(GlobalObjectId.GetGlobalObjectIdSlow(pipeline).ToString());
            }
            else
            {
                return(step.GetType().GetFullyQualifedAssemblyTypeName());
            }
        }
Exemple #18
0
        public void SetUpOnce()
        {
#if UNITY_EDITOR
            try
            {
                BuildConfiguration.CreateAsset(m_BuildConfigPath, config =>
                {
                    config.SetComponent(new SceneList
                    {
                        SceneInfos = new List <SceneList.SceneInfo>
                        {
                            new SceneList.SceneInfo
                            {
                                Scene = GlobalObjectId.GetGlobalObjectIdSlow(
                                    AssetDatabase.LoadAssetAtPath <SceneAsset>(m_SubScenePath))
                            }
                        }
                    });
                });
                m_BuildConfigurationGUID = new GUID(AssetDatabase.AssetPathToGUID(m_BuildConfigPath));
                m_SceneGUID = new GUID(AssetDatabase.AssetPathToGUID(m_SubScenePath));

                var guid = SceneWithBuildConfigurationGUIDs.EnsureExistsFor(m_SceneGUID, m_BuildConfigurationGUID, true,
                                                                            out var requestRefresh);
                if (requestRefresh)
                {
                    AssetDatabase.Refresh();
                }
                m_SceneWithBuildSettingsPath = SceneWithBuildConfigurationGUIDs.GetSceneWithBuildSettingsPath(guid);
                EntityScenesPaths.GetSubSceneArtifactHash(m_SceneGUID, m_BuildConfigurationGUID, true,
                                                          ImportMode.Synchronous);
            }
            catch
            {
                AssetDatabase.DeleteAsset(m_TempPath);
                AssetDatabase.DeleteAsset(m_SceneWithBuildSettingsPath);
                throw;
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
#else
            //TODO: Playmode test not supported yet
            m_SceneGUID = new Unity.Entities.Hash128();
#endif
        }
Exemple #19
0
        internal static string Serialize(IBuildStep step)
        {
            if (step == null)
            {
                return(null);
            }

            if (step is BuildPipeline pipeline)
            {
                return(GlobalObjectId.GetGlobalObjectIdSlow(pipeline).ToString());
            }
            else
            {
                var type = step.GetType();
                return($"{type}, {type.Assembly.GetName().Name}");
            }
        }
        public void Serialize(JsonStringBuffer writer, IBuildStep value)
        {
            string json = null;

            if (value != null)
            {
                if (value is BuildPipeline pipeline)
                {
                    json = GlobalObjectId.GetGlobalObjectIdSlow(pipeline).ToString();
                }
                else
                {
                    json = value.GetType().GetQualifedAssemblyTypeName();
                }
            }
            writer.WriteEncodedJsonString(json);
        }
Exemple #21
0
        /// <summary>
        /// Gets the current scene infos for the build. If BuildCurrentScene is checked, all open scenes are returned.
        /// </summary>
        /// <returns>The array of SceneInfos.</returns>
        public SceneInfo[] GetSceneInfosForBuild()
        {
            if (BuildCurrentScene)
            {
                // Build a list of the root scenes
                var rootScenes = new List <SceneInfo>();
                for (int i = 0; i != EditorSceneManager.sceneCount; i++)
                {
                    var scene = EditorSceneManager.GetSceneAt(i);

                    if (scene.isSubScene)
                    {
                        continue;
                    }
                    if (!scene.isLoaded)
                    {
                        continue;
                    }
                    if (EditorSceneManager.IsPreviewScene(scene))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(scene.path))
                    {
                        continue;
                    }
                    var sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(scene.path);
                    rootScenes.Add(new SceneInfo()
                    {
                        AutoLoad = true, Scene = GlobalObjectId.GetGlobalObjectIdSlow(sceneAsset)
                    });
                }

                return(rootScenes.ToArray());
            }
            else
            {
                return(SceneInfos.ToArray());
            }
        }
Exemple #22
0
        public void JsonSerialization_Serialize_UnityEngineObject_FromGlobalObjectId()
        {
            var src = new UnityEditorGlobalObjectIdContainer {
                Value = GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath <Texture2D>(k_AssetPath))
            };
            var json = JsonSerialization.Serialize(src);

            Debug.Log(json);
            Assert.That(json, Does.Match(@".*""GlobalObjectId_V\d-\d-[\da-f]{32}-\d{7}-\d"".*"));

            var dst = new UnityEditorGlobalObjectIdContainer();

            using (JsonSerialization.DeserializeFromString(json, ref dst))
            {
                Assert.That(dst.Value, Is.Not.EqualTo(new GlobalObjectId()));

                var obj = GlobalObjectId.GlobalObjectIdentifierToObjectSlow(dst.Value);
                Assert.That(obj, Is.Not.Null);
                Assert.That(obj, Is.Not.False);
                Assert.That(AssetDatabase.GetAssetPath(obj), Is.EqualTo(k_AssetPath));
            }
        }
Exemple #23
0
    static void RunSyncSceneList()
    {
        //Get selected object on ProjectView
        var selected = Selection.activeObject;

        if (selected.GetType() != typeof(BuildConfiguration))
        {
            Debug.LogError("Cannot sync scenelist. You've selected " + selected.name +
                           " which is not a BuildConfiguration asset. Please select a BuildConfiguration asset on ProjectView and try again.");
            return;
        }

        //Get Buildconfig asset
        BuildConfiguration config = (BuildConfiguration)selected;

        //Get scenelist from BuildSettings
        EditorBuildSettingsScene[] buildSettingScenes = EditorBuildSettings.scenes;
        List <SceneList.SceneInfo> scenelist          = new List <SceneList.SceneInfo>();

        for (int i = 0; i < buildSettingScenes.Length; i++)
        {
            var sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(buildSettingScenes[i].path);
            scenelist.Add(new SceneList.SceneInfo()
            {
                AutoLoad = false, Scene = GlobalObjectId.GetGlobalObjectIdSlow(sceneAsset)
            });
        }

        //Set the scenelist on Buildconfig asset
        var sceneListComponent = config.GetComponent <SceneList>();

        sceneListComponent.SceneInfos = scenelist;
        config.SetComponent <SceneList>(sceneListComponent);
        config.SaveAsset();
        AssetDatabase.Refresh();

        //Log
        Debug.Log("Successfully synced " + buildSettingScenes.Length + " scenes to scenelist on " + AssetDatabase.GetAssetPath(config) + " asset.");
    }
Exemple #24
0
        public ComponentID(Component comp)
        {
            component = comp;
            goid      = GlobalObjectId.GetGlobalObjectIdSlow(comp);

            if (alive) // пациент скорее жив, чем мёртв?
            {
                type          = component.GetType();
                metadataToken = type.MetadataToken;
                var serComp = new SerializedObject(comp);
                mScript = serComp.FindProperty(SceneFile.unitMonoScriptField);
                if (mScript != null)
                {
                    guid = SceneFile.current.GetComponentGUID(fileID, false);
                }
            }
            else // пациент мёртв, мы нашли битый скрипт
            {
                type          = null;
                metadataToken = -1;
                mScript       = null;
            }
        }
Exemple #25
0
    public static EntityGuid GetEntityGuid(UnityObject uobject, int index)
    {
#if false
        var id = GlobalObjectId.GetGlobalObjectIdSlow(go);
        // For the time being use InstanceID until we support GlobalObjectID API
        //Debug.Log(id);
        var    idStr             = $"{id}:{index}";
        byte[] bytes             = System.Text.Encoding.ASCII.GetBytes(idStr);
        UnityEngine.Hash128 hash = UnityEngine.Hash128.Compute(idStr);

        EntityGuid entityGuid;
        Assert.AreEqual(sizeof(EntityGuid), sizeof(UnityEngine.Hash128));
        UnsafeUtility.MemCpy(&entityGuid, &hash, sizeof(UnityEngine.Hash128));

        return(entityGuid);
#else
        EntityGuid entityGuid;
        entityGuid.a = (ulong)uobject.GetInstanceID();
        entityGuid.b = (ulong)index;

        return(entityGuid);
#endif
    }
    private static void SyncSceneList(bool applyToAll = true)
    {
        EditorBuildSettingsScene[] buildSettingScenes = EditorBuildSettings.scenes;
        List <SceneList.SceneInfo> scenelist          = new List <SceneList.SceneInfo>();

        for (int i = 0; i < buildSettingScenes.Length; i++)
        {
            var sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(buildSettingScenes[i].path);
            scenelist.Add(new SceneList.SceneInfo()
            {
                AutoLoad = false, Scene = GlobalObjectId.GetGlobalObjectIdSlow(sceneAsset)
            });
        }

        if (applyToAll)
        {
            var assets = AssetDatabase.FindAssets("t:BuildConfiguration", new[] { "Assets/Tests/Editor" });
            foreach (var guid in assets)
            {
                var c = AssetDatabase.LoadAssetAtPath <BuildConfiguration>(AssetDatabase.GUIDToAssetPath(guid));
                var sceneListComponent = c.GetComponent <SceneList>();
                sceneListComponent.SceneInfos = scenelist;
                c.SetComponent <SceneList>(sceneListComponent);
                c.SaveAsset();
            }
            AssetDatabase.Refresh();
            Log("*************** SetupGraphicsTestCases - Synced " + buildSettingScenes.Length + " scenes to scenelist on " + assets.Length + " Assets/Tests/Editor/ BuildConfig assets.");
        }
        else
        {
            //Yamato will run this
            var sceneListComponent = config.GetComponent <SceneList>();
            sceneListComponent.SceneInfos = scenelist;
            config.SetComponent <SceneList>(sceneListComponent);
            Log("*************** SetupGraphicsTestCases - Synced " + buildSettingScenes.Length + " scenes to scenelist");
        }
    }
Exemple #27
0
        private void Initialize(UnityObject[] targets)
        {
            Ensure.That(nameof(targets)).IsNotNull(targets);
            Ensure.That(nameof(targets)).HasItems(targets);

            initializationTargets = targets;

#if UNITY_2019_2_OR_NEWER
            initializationTargetIdData = targets.Select(t => t == null ? null : GlobalObjectId.GetGlobalObjectIdSlow(t).ToString()).ToArray();
#endif

            editor = Editor.CreateEditor(targets);

            AssetImporter importer = null;

            foreach (var target in targets)
            {
                var path = AssetDatabase.GetAssetPath(target);

                if (path == null || AssetDatabase.IsSubAsset(target))
                {
                    continue;
                }

                importer = AssetImporter.GetAtPath(path);

                if (importer != null)
                {
                    break;
                }
            }

            if (importer != null)
            {
                // Comment from AssetImporterEditor.cs (reference source) about InternalSetAssetImporterTargetEditor:
                // "Called from ActiveEditorTracker.cpp to setup the target editor once created before Awake and OnEnable of the Editor."

                Editor importerEditor = null;

                try
                {
                    importerEditor = Editor.CreateEditor(importer);
                }
                catch (Exception ex)
                {
                    // Unfortunately we cannot hook our call before Awake, so there might be some unexpected behaviour.
                    // PrefabImporterEditor would need it, for example, to iterate over assetTargets in Awake(), and will NRE:
                    // https://support.ludiq.io/communities/41/topics/5246-

                    Debug.Log(ex.GetType() + " " + importerEditor.GetType());

                    if (ex is NullReferenceException &&
                        importerEditor != null &&
                        importerEditor.GetType().Name == "PrefabImporterEditor")
                    {
                        // Eat the known issue.
                    }
                    else
                    {
                        throw;
                    }
                }

                if (importerEditor is AssetImporterEditor)
                {
                    var importerEditorDynamic = importerEditor.AsDynamic();
                    importerEditorDynamic.InternalSetAssetImporterTargetEditor(editor);
                    importerTargetEditor = editor;
                    editor = importerEditor;
                }
            }

            var dynamicEditor = editor.AsDynamic();
            dynamicEditor.firstInspectedEditor = true;

            if (targets.Length == 1)
            {
                var target = targets[0];
                titleContent.text = $"{target.name} ({target.GetType().DisplayName()})";
            }
            else
            {
                titleContent.text = "(Multiple)";
            }
        }
Exemple #28
0
        public static void SetUpOnce()
        {
            s_Assets.SetUp();

            var assetGuids = new List <GUID>();

            try
            {
                {
                    string path = s_Assets.GetNextPath(".asset");
                    AssetDatabase.CreateAsset(s_TempTexture = new Texture2D(64, 64), path);
                    s_TempTextureGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempTextureGuid);
                }
                {
                    string path = s_Assets.GetNextPath(".mat");
                    AssetDatabase.CreateAsset(s_TempMaterial = new Material(Shader.Find("Standard")), path);
                    s_TempMaterialGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempMaterialGuid);
                    s_TempMaterial.mainTexture = s_TempTexture;
                }

                var tempScenePath = s_Assets.GetNextPath(".unity");
                s_TempScene            = SubSceneTestsHelper.CreateScene(tempScenePath);
                s_SubSceneWithSections = SubSceneTestsHelper.CreateSubSceneInSceneFromObjects("SubScene", false, s_TempScene, () =>
                {
                    var go1 = new GameObject();
                    go1.AddComponent <SceneSectionComponent>().SectionIndex = 0;
                    var go2 = new GameObject();
                    go2.AddComponent <SceneSectionComponent>().SectionIndex = 2;
                    go2.AddComponent <TestComponentAuthoring>().Material    = s_TempMaterial;
                    return(new List <GameObject> {
                        go1, go2
                    });
                });

                {
                    var path = s_Assets.GetNextPath("LiveLinkBuildConfig.buildconfiguration");
                    BuildConfiguration.CreateAsset(path, config =>
                    {
                        config.SetComponent(new SceneList
                        {
                            SceneInfos = new List <SceneList.SceneInfo>
                            {
                                new SceneList.SceneInfo
                                {
                                    Scene = GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath <SceneAsset>(tempScenePath))
                                }
                            }
                        });
                    });
                    s_LiveLinkBuildConfigGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                }
            }
            catch
            {
                s_Assets.TearDown();
                throw;
            }

            // This call ensures that the asset worker is already running and no test times out because we're still
            // waiting for the asset worker. Effectively this doesn't change the runtime that much since we will have
            // to wait for the import to finish in most of the tests anyway.
            GetLiveLinkArtifactHash(s_TempMaterialGuid, ImportMode.Synchronous);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            s_TempAssetGuids = assetGuids.ToArray();
        }
Exemple #29
0
    static void DumpGOID()
    {
        var goid = GlobalObjectId.GetGlobalObjectIdSlow(Selection.activeObject);

        Debug.Log(goid);
    }
Exemple #30
0
        public override void IndexDocument(string path, bool checkIfDocumentExists)
        {
            int assetInstanceId = Utils.GetMainAssetInstanceID(path);
            var globalObjectId  = GlobalObjectId.GetGlobalObjectIdSlow(assetInstanceId);
            var documentIndex   = AddDocument(globalObjectId.ToString(), null, path, checkIfDocumentExists, SearchDocumentFlags.Asset);

            if (documentIndex < 0)
            {
                return;
            }

            AddSourceDocument(path, GetDocumentHash(path));

            var fileName = Path.GetFileName(path);

            IndexWordComponents(documentIndex, fileName);
            IndexProperty(documentIndex, "name", Path.GetFileNameWithoutExtension(fileName), saveKeyword: true, exact: true);

            if (path.StartsWith("Packages/", StringComparison.Ordinal))
            {
                IndexProperty(documentIndex, "a", "packages", saveKeyword: true, exact: true);
            }
            else
            {
                IndexProperty(documentIndex, "a", "assets", saveKeyword: true, exact: true);
            }

            var fi = new FileInfo(path);

            if (fi.Exists)
            {
                IndexNumber(documentIndex, "size", (double)fi.Length);
                IndexProperty(documentIndex, "ext", fi.Extension.Replace(".", ""), saveKeyword: false, exact: true);
                IndexNumber(documentIndex, "age", (DateTime.Now - fi.LastWriteTime).TotalDays);

                foreach (var dir in Path.GetDirectoryName(path).Split(new[] { '/', '\\' }).Skip(1).Reverse().Take(3))
                {
                    IndexProperty(documentIndex, "dir", dir, saveKeyword: false, exact: true);
                }

                IndexProperty(documentIndex, "t", "file", saveKeyword: true, exact: true);
            }
            else if (Directory.Exists(path))
            {
                IndexProperty(documentIndex, "t", "folder", saveKeyword: true, exact: true);
            }

            var at = AssetDatabase.GetMainAssetTypeAtPath(path);
            var hasCustomIndexers = HasCustomIndexers(at);
            var isPrefab          = path.EndsWith(".prefab");

            if (at != null)
            {
                IndexWordComponents(documentIndex, at.Name);
                IndexTypes(at, documentIndex);

                if (settings.options.types)
                {
                    foreach (var obj in AssetDatabase.LoadAllAssetRepresentationsAtPath(path).Where(o => o))
                    {
                        IndexTypes(obj.GetType(), documentIndex);

                        if (AssetDatabase.IsSubAsset(obj))
                        {
                            IndexSubAsset(obj, path, checkIfDocumentExists, hasCustomIndexers);
                        }
                        else if (!string.IsNullOrEmpty(obj.name))
                        {
                            IndexProperty(documentIndex, "name", obj.name, saveKeyword: true, exact: true);
                        }
                    }

                    if (isPrefab)
                    {
                        var rootPrefabObject = AssetDatabase.LoadAssetAtPath <GameObject>(path);
                        if (rootPrefabObject)
                        {
                            var gocs = rootPrefabObject.GetComponents <Component>();
                            for (int componentIndex = 1; componentIndex < gocs.Length; ++componentIndex)
                            {
                                var c = gocs[componentIndex];
                                if (!c || (c.hideFlags & (HideFlags.DontSave | HideFlags.HideInInspector)) != 0)
                                {
                                    continue;
                                }
                                IndexProperty(documentIndex, "t", c.GetType().Name, saveKeyword: true);
                            }
                        }
                    }
                }
            }

            IndexLabels(documentIndex, path);
            IndexBundles(documentIndex, path);

            if (settings.options.properties || hasCustomIndexers)
            {
                IndexProperties(documentIndex, path, hasCustomIndexers);
            }

            if (settings.options.extended)
            {
                IndexSceneDocument(path, checkIfDocumentExists);
            }

            if (settings.options.dependencies)
            {
                IndexDependencies(documentIndex, path);
            }
        }