Example #1
0
            static void ValidateGameObject(Transform transform, object userData)
            {
                GameObject go = transform.gameObject;

                if (!EditorSceneManager.IsPreviewSceneObject(go))
                {
                    m_Errors.Add("   GameObject not correctly marked as PreviewScene object: " + go.name);
                }

                var components = go.GetComponents <Component>();

                foreach (var c in components)
                {
                    if (c == null)
                    {
                        // This can happen if a monobehaviour has a missing script.
                        // In this case the check can not be made. Could be fixed
                        // by moving the component iteration to native code.
                        continue;
                    }
                    if (!EditorSceneManager.IsPreviewSceneObject(c))
                    {
                        m_Errors.Add(string.Format("   Component {0} not correctly marked as PreviewScene object: (GameObject: {1})", c.GetType().Name, go.name));
                    }
                }
            }
Example #2
0
        public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject go)
        {
#if UNITY_EDITOR
            var gameObject = tilemap.GetComponent <Tilemap>().gameObject;

            if (!Application.isPlaying || EditorSceneManager.IsPreviewSceneObject(gameObject))
            {
                return(true);
            }
#endif
            //刷新地图的可行走度
            if (GameMapManager.gameMapManager != null)
            {
                var currentTileInfo =
                    GameMapManager.gameMapManager.InfoTilemap.GetTileInfo(new Vector2Int(position.x, position.y));

                if (currentTileInfo.tileType == InfoTile.TileType.Ground ||
                    currentTileInfo.tileType == InfoTile.TileType.Void)
                {
                    GameMapManager.gameMapManager.InfoTilemap.SetTileInfo(new Vector2Int(position.x, position.y),
                                                                          tileType,
                                                                          currentTileInfo.hasActor);
                }
            }

            return(true);
        }
        protected static System.Collections.Generic.IEnumerable <T> GetObjectsForLightingExplorer <T>() where T : UnityEngine.Component
        {
            var objects = Resources.FindObjectsOfTypeAll <T>().Where((T obj) =>
            {
                return(!EditorUtility.IsPersistent(obj) && !obj.hideFlags.HasFlag(HideFlags.HideInHierarchy) && !obj.hideFlags.HasFlag(HideFlags.HideAndDontSave));
            });

            var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();

            // No prefab mode.
            if (prefabStage == null)
            {
                // Return all object instances in the scene including prefab instances, but not those that are in prefab assets.
                return(objects);
            }
            // In Context prefab mode with Normal rendering mode
            else if (prefabStage.mode == PrefabStage.Mode.InContext &&
                     StageNavigationManager.instance.contextRenderMode == StageUtility.ContextRenderMode.Normal)
            {
                // Return all object instances in the scene and objects in the opened prefab asset, but not objects in the opened prefab instance.
                return(objects.Where((T obj) =>
                {
                    return !StageUtility.IsPrefabInstanceHiddenForInContextEditing(obj.gameObject);
                }));
            }
            // All remaining cases, e.g. In Context with Hidden or GrayedOut rendering mode, or In Isolation prefab mode.
            else
            {
                // Return only objects in the opened prefab asset.
                return(objects.Where((T obj) =>
                {
                    return EditorSceneManager.IsPreviewSceneObject(obj);
                }));
            }
        }
Example #4
0
        public void AddData()
        {
#if UNITY_EDITOR
            var isInPreviewScene = EditorSceneManager.IsPreviewSceneObject(this);
            var isPrefab         = isInPreviewScene || EditorUtility.IsPersistent(this);
            if (isPrefab)
            {
                //Debug.LogFormat("NavMeshData from {0}.{1} will not be added to the NavMesh world because the gameObject is a prefab.",
                //    gameObject.name, name);
                return;
            }
#endif
            if (m_NavMeshDataInstance.valid)
            {
                return;
            }

            if (m_NavMeshData != null)
            {
                m_NavMeshDataInstance       = NavMesh.AddNavMeshData(m_NavMeshData, transform.position, transform.rotation);
                m_NavMeshDataInstance.owner = this;
            }

            m_LastPosition = transform.position;
            m_LastRotation = transform.rotation;
        }
Example #5
0
        public EObjectStage GetObjectStage()
        {
#if UNITY_EDITOR
            if (EditorUtility.IsPersistent(gameObject))
            {
                return(EObjectStage.PRESISTENCE_STAGE);
            }

            // If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it
            var mainStage    = StageUtility.GetMainStageHandle();
            var currentStage = StageUtility.GetStageHandle(gameObject);
            if (currentStage == mainStage)
            {
                if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                {
                    var type = PrefabUtility.GetPrefabAssetType(gameObject);
                    var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject));
                    //Debug.Log(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path));
                    return(EObjectStage.MAIN_STAGE);
                }
                else
                {
                    //Debug.Log("GameObject is a plain GameObject in the MainStage");
                    return(EObjectStage.MAIN_STAGE);
                }
            }
            else
            {
                var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject);
                if (prefabStage != null)
                {
                    if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                    {
                        var type             = PrefabUtility.GetPrefabAssetType(gameObject);
                        var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject));
                        //Debug.Log(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath));
                        return(EObjectStage.PREFAB_STAGE);
                    }
                    else
                    {
                        var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath);
                        var type            = PrefabUtility.GetPrefabAssetType(prefabAssetRoot);
                        //Debug.Log(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath));
                        return(EObjectStage.PREFAB_STAGE);
                    }
                }
                else if (EditorSceneManager.IsPreviewSceneObject(gameObject))
                {
                    //Debug.Log("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities.");
                    return(EObjectStage.OTHER_STAGE);
                }
                else
                {
                    LogConsoleError("Unknown GameObject Info");
                }
            }
#endif
            return(EObjectStage.OTHER_STAGE);
        }
Example #6
0
    static public void PrintGameObjectInfo()
    {
        var go = Selection.activeGameObject;

        if (go == null)
        {
            Debug.Log("Please select a GameObject");
            return;
        }

        var mainStage = StageUtility.GetMainStageHandle();

        // Lets determine which stage we are in first because getting Prefab info depends on it
        var currentStage = StageUtility.GetStageHandle(go);

        if (currentStage == mainStage)
        {
            if (PrefabUtility.IsPartOfPrefabInstance(go))
            {
                var type = PrefabUtility.GetPrefabAssetType(go);
                var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(go));
                Debug.Log(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path));
            }
            else
            {
                Debug.Log("Selected GameObject is a plain GameObject in the MainStage");
            }
        }
        else
        {
            var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(go);
            if (prefabStage != null)
            {
                if (PrefabUtility.IsPartOfPrefabInstance(go))
                {
                    var type             = PrefabUtility.GetPrefabAssetType(go);
                    var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(go));
                    Debug.Log(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath));
                }
                else
                {
                    var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath);
                    var type            = PrefabUtility.GetPrefabAssetType(prefabAssetRoot);
                    Debug.Log(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath));
                }
            }
            else if (EditorSceneManager.IsPreviewSceneObject(go))
            {
                Debug.Log("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities.");
            }
            else
            {
                Debug.LogError("Unknown GameObject Info");
            }
        }
    }
        public override void OnInspectorGUI()
        {
            var isPartOfPrefab = PrefabUtility.IsPartOfAnyPrefab(target);
            var isPreviewMode  = EditorSceneManager.IsPreviewSceneObject(target);

            if (isPartOfPrefab && !isPreviewMode)
            {
                EditorGUILayout.HelpBox("Open prefab for editing support", MessageType.Info);
            }
            else
            {
                serializedObject.Update();

                EditorGUILayout.PropertyField(Container);
                GUI.enabled = Container.objectReferenceValue != null;

                EditorGUILayout.PropertyField(Current);

                var widgets = WidgetsLibrary.Widgets;
                var names   = widgets.Select(x => x.Name).ToList();
                var ids     = widgets.Select(x => x.Id).ToList();

                var guiColor = GUI.color;
                var index    = ids.IndexOf(PropertyId.stringValue);
                if (index < 0)
                {
                    names.Insert(0, "UNDEFINED");
                    ids.Insert(0, Guid.Empty.ToString());
                    index     = 0;
                    GUI.color = Color.yellow;
                }

                var selectedIndex = EditorGUILayout.Popup("Widgets", index, names.ToArray());
                if (selectedIndex != index)
                {
                    PropertyId.stringValue = ids[selectedIndex];
                    serializedObject.ApplyModifiedProperties();

                    var container = target as WidgetContainer;
                    if (container)
                    {
                        WidgetsHandler.Handle(container);
                    }
                }

                GUI.color   = guiColor;
                GUI.enabled = true;

                serializedObject.ApplyModifiedProperties();
            }
        }
Example #8
0
        bool UnshareNavMeshAsset()
        {
            // Nothing to unshare
            if (m_NavMeshData == null)
            {
                return(false);
            }

            // Prefab parent owns the asset reference
#if UNITY_2018_3_OR_NEWER
            var isInPreviewScene   = EditorSceneManager.IsPreviewSceneObject(this);
            var isPersistentObject = EditorUtility.IsPersistent(this);
            if (isInPreviewScene || isPersistentObject)
            {
                return(false);
            }
#else
            // Prefab parent owns the asset reference
            var prefabType = UnityEditor.PrefabUtility.GetPrefabType(this);
            if (prefabType == UnityEditor.PrefabType.Prefab)
            {
                return(false);
            }
#endif

            // An instance can share asset reference only with its prefab parent
#if UNITY_2018_2_OR_NEWER
            var prefab = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(this) as NavMeshSurface;
#else
            var prefab = UnityEditor.PrefabUtility.GetPrefabParent(this) as NavMeshSurface;
#endif
            if (prefab != null && prefab.navMeshData == navMeshData)
            {
                return(false);
            }

            // Don't allow referencing an asset that's assigned to another surface
            for (var i = 0; i < s_NavMeshSurfaces.Count; ++i)
            {
                var surface = s_NavMeshSurfaces[i];
                if (surface != this && surface.m_NavMeshData == m_NavMeshData)
                {
                    return(true);
                }
            }

            // Asset is not referenced by known surfaces
            return(false);
        }
Example #9
0
        static void CreateElement()
        {
            if (GameObject.Find("The Vegetation Engine") == null)
            {
                Debug.Log("[Warning][The Vegetation Engine] " + "The Vegetation Engine manager is missing from your scene. Make sure setup it up first!");
                return;
            }

            GameObject element = MonoBehaviour.Instantiate(Resources.Load <GameObject>("Internal Element"));

            var sceneCamera = SceneView.lastActiveSceneView.camera;

            if (sceneCamera != null)
            {
                element.transform.position = sceneCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f));
            }
            else
            {
                element.transform.localPosition    = Vector3.zero;
                element.transform.localEulerAngles = Vector3.zero;
                element.transform.localScale       = Vector3.one;
            }

            if (Selection.activeGameObject != null)
            {
                element.transform.parent = Selection.activeGameObject.transform;
            }

            if (EditorSceneManager.IsPreviewSceneObject(element))
            {
                Debug.Log("[Warning][The Vegetation Engine] " + "Elements cannot be created inside prefabs");
            }
            else
            {
                element.name = "Element";
                element.AddComponent <TVEElement>();
            }

            Selection.activeGameObject = element;

            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
        }
Example #10
0
        static void Register(NavMeshSurface surface)
        {
#if UNITY_EDITOR
            var isInPreviewScene = EditorSceneManager.IsPreviewSceneObject(surface);
            var isPrefab         = isInPreviewScene || EditorUtility.IsPersistent(surface);
            if (isPrefab)
            {
                //Debug.LogFormat("NavMeshData from {0}.{1} will not be added to the NavMesh world because the gameObject is a prefab.",
                //    surface.gameObject.name, surface.name);
                return;
            }
#endif
            if (s_NavMeshSurfaces.Count == 0)
            {
                NavMesh.onPreUpdate += UpdateActive;
            }

            if (!s_NavMeshSurfaces.Contains(surface))
            {
                s_NavMeshSurfaces.Add(surface);
            }
        }
Example #11
0
        /// <summary>
        /// Returns the environment this GameObject exists in.
        /// </summary>
        public static GameObjectEnvironments GetGameObjectEnvironment(this GameObject gameObject)
        {
            //based on https://github.com/Unity-Technologies/PrefabAPIExamples/blob/master/Assets/Scripts/GameObjectTypeLogging.cs
            //most comments also from there

            GameObjectEnvironments environment;

#if UNITY_EDITOR
            //check if game object exists on disk
            if (EditorUtility.IsPersistent(gameObject))
            {
                if (!PrefabUtility.IsPartOfPrefabAsset(gameObject))
                {
                    //The GameObject is a temporary object created during import.
                    //OnValidate() is called two times with a temporary object during import:
                    //	First time is when saving cloned objects to .prefab file.
                    //	Second event is when reading .prefab file objects during import
                    environment = GameObjectEnvironments.PrefabImport;
                }
                else
                {
                    //GameObject is part of an imported Prefab Asset (from the Library folder)
                    environment = GameObjectEnvironments.PrefabAsset;
                }
            }

            else
            {
                //If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it
                StageHandle mainStage    = StageUtility.GetMainStageHandle();
                StageHandle currentStage = StageUtility.GetStageHandle(gameObject);

                if (currentStage == mainStage)
                {
                    //viewing scenes in the main stage (aka -not- editing in prefab mode)
                    if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                    {
                        //GameObject is part of a Prefab Instance in the MainStage
                        environment = GameObjectEnvironments.PrefabInstance;
                    }
                    else
                    {
                        //GameObject is a plain GameObject in the MainStage
                        environment = GameObjectEnvironments.Scene;
                    }
                }

                else
                {
                    //editing a prefab in prefab mode
                    PrefabStage prefabStage = PrefabStageUtility.GetPrefabStage(gameObject);

                    if (prefabStage != null)
                    {
                        if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                        {
                            //GameObject is in a PrefabStage and is nested.
                            environment = GameObjectEnvironments.NestedPrefabStage;
                        }
                        else
                        {
                            //GameObject is in a PrefabStage.
                            environment = GameObjectEnvironments.PrefabStage;
                        }
                    }

                    else if (EditorSceneManager.IsPreviewSceneObject(gameObject))
                    {
                        //GameObject is not in the MainStage, nor in a PrefabStage.
                        //But it is in a PreviewScene so could be used for Preview rendering or other utilities.
                        environment = GameObjectEnvironments.PreviewScene;
                    }

                    else
                    {
                        //Unknown GameObject Info
                        environment = GameObjectEnvironments.Unknown;
                    }
                }
            }
#else
            //Can't do any of the above checks outside of the editor
            environment = GameObjectEnvironments.Unknown;
#endif

            return(environment);
        }
Example #12
0
        public static async void DoConvert(ClassBind instance)
        {
            int affectCounts = 0;

            foreach (var _cb in instance.ScriptsToBind) //遍历
            {
                string   className = $"{_cb.Namespace}.{_cb.Class}";
                Assembly hotCode   = Assembly
                                     .LoadFile("Assets/HotUpdateResources/Dll/Hidden~/HotUpdateScripts.dll");
                Type t = hotCode.GetType(className); //加载热更类

                if (t == null)
                {
                    EditorUtility.DisplayDialog("ClassBind Error", $"Class {className} does not exist " +
                                                $"in hot update scripts solution!\n" +
                                                $"'{className}'类在热更工程中不存在", "OK");
                    return;
                }

                //热更实例
                object hotInstance = null;
                if (!t.IsSubclassOf(hotCode.GetType("JEngine.Core.JBehaviour"))) //JBehaviour派生类不构造对象,不进行赋值
                {
                    hotInstance = Activator.CreateInstance(t);
                }

                var fieldsInCb = _cb.Fields.Select(f => f.fieldName).ToList(); //全部已经设置的字段
                var fs         = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance |
                                             BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                var ps = t.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance |
                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

                foreach (var field in fs)
                {
                    //遍历字段

                    EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                     "Converting FieldInfos " + fs.ToList().IndexOf(field) + "/" + fs.Length,
                                                     (float)fs.ToList().IndexOf(field) / (float)fs.Length);

                    if (!fieldsInCb.Contains(field.Name))
                    {
                        _ClassField cf        = new _ClassField();
                        string      fieldName = field.Name;
                        cf.fieldName = fieldName;

                        SetType(cf, field.FieldType, hotCode);
                        SetVal(ref cf, field, hotCode, hotInstance);

                        _cb.Fields.Add(cf);
                        affectCounts++;
                    }

                    await Task.Delay(10); //延迟一下,动画更丝滑
                }

                EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                 $"Converting FieldInfos {fs.Length}/{fs.Length}", 1);

                await Task.Delay(50); //延迟一下,动画更丝滑

                foreach (var property in ps)
                {
                    //遍历属性
                    EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                     "Converting PropertyInfos " + ps.ToList().IndexOf(property) + "/" + ps.Length,
                                                     (float)ps.ToList().IndexOf(property) / (float)ps.Length);
                    if (!fieldsInCb.Contains(property.Name))
                    {
                        _ClassField cf        = new _ClassField();
                        string      fieldName = property.Name;
                        cf.fieldName = fieldName;

                        SetType(cf, property.PropertyType, hotCode);
                        SetVal(ref cf, property, hotCode, hotInstance);

                        _cb.Fields.Add(cf);
                        affectCounts++;
                    }

                    await Task.Delay(10); //延迟一下,动画更丝滑
                }

                EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                 $"Converting PropertyInfos {ps.Length}/{ps.Length}", 1);

                await Task.Delay(50); //延迟一下,动画更丝滑

                EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                 $"Processing next class", 1);

                await Task.Delay(150); //延迟一下,动画更丝滑
            }

            await Task.Delay(50); //延迟一下,动画更丝滑

            EditorUtility.ClearProgressBar();

            //转换后保存场景
            bool saveResult = false;

            AssetDatabase.SaveAssets();
            bool isPreviewSceneObject = EditorSceneManager.IsPreviewSceneObject(Selection.activeGameObject);

            if (PrefabUtility.IsPartOfAnyPrefab(instance.gameObject) || PrefabUtility.IsPartOfPrefabAsset(instance.gameObject))
            {
                PrefabUtility.SavePrefabAsset(instance.gameObject, out saveResult);
            }
            else if (isPreviewSceneObject)
            {
                EditorSceneManager.SaveOpenScenes();
            }
            else
            {
                var scene = EditorSceneManager.GetActiveScene();
                saveResult = EditorSceneManager.SaveScene(scene, scene.path);
            }

            string result   = saveResult ? "succeeded" : "failed";
            string resultZh = saveResult ? "成功" : "失败";

            EditorUtility.DisplayDialog("ClassBind Result",
                                        $"Added {affectCounts} fields into ClassBind: {instance.name} and saved the scene {result}\n" +
                                        $"ClassBind: {instance.name}的fields添加了{affectCounts}个,且保存{resultZh}",
                                        "Done");
        }
        static string GetWarning(GameObject gameObject)
        {
            // only care about scene objects
            if (gameObject == null)
            {
                return(null);
            }

            // assets have no scene context
            if (gameObject.IsPrefab())
            {
                return(null);
            }

            // editing in a preview scene (like a prefab in isolation mode) also has no context
            if (EditorSceneManager.IsPreviewSceneObject(gameObject))
            {
                return(null);
            }

            var isSubScene = EditorEntityScenes.IsEntitySubScene(gameObject.scene);

            gameObject.GetComponentsInParent(true, s_ConvertToEntityBuffer);
            var convertToEntity = s_ConvertToEntityBuffer.Count > 0;

            s_ConvertToEntityBuffer.Clear();

            var willBeConverted = convertToEntity | isSubScene;

            if (!willBeConverted)
            {
                Type convertType = null;
                foreach (var behaviour in gameObject.GetComponents <MonoBehaviour>())
                {
                    if (behaviour != null && behaviour.GetType().GetCustomAttribute <RequiresEntityConversionAttribute>(true) != null)
                    {
                        convertType = behaviour.GetType();
                        break;
                    }
                }

                if (convertType != null)
                {
                    return
                        ($"The {convertType.Name} component on '{gameObject.name}' is meant for entity conversion, " +
                         $"but it is not part of a {nameof(SubScene)} or {nameof(ConvertToEntity)} component.\n" +
                         $"Please move the {nameof(GameObject)} to a {nameof(SubScene)} or add the {nameof(ConvertToEntity)} component.");
                }
            }

            if (isSubScene && convertToEntity)
            {
                return
                    ($"'{gameObject.name}' will be converted due to being in a {nameof(SubScene)}. {nameof(ConvertToEntity)} " +
                     $"will have no effect. Please remove the {nameof(ConvertToEntity)} component.");
            }

            if (isSubScene && gameObject.GetComponent <GameObjectEntity>() != null)
            {
                return
                    ($"'{gameObject.name}' will be converted due to being in a {nameof(SubScene)}. {nameof(GameObjectEntity)} " +
                     $"will have no effect the {nameof(GameObject)} will not be loaded.\nPlease remove the {nameof(GameObjectEntity)} component");
            }

            if (convertToEntity && gameObject.GetComponent <GameObjectEntity>() != null)
            {
                return
                    ($"'{gameObject.name}' will be converted due to being in a {nameof(ConvertToEntity)} hierarchy. " +
                     $"{nameof(GameObjectEntity)} will have no effect.\nPlease remove the {nameof(GameObjectEntity)} component.");
            }

            return(null);
        }
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;
            RendererLighting.Setup(m_RendererData);

            CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting");
            cmd.Clear();

            Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures");
            RendererLighting.CreateRenderTextures(cmd, camera);
            Profiler.EndSample();

            cmd.SetGlobalFloat("_HDREmulationScale", m_RendererData.hdrEmulationScale);
            cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_RendererData.hdrEmulationScale);


#if UNITY_EDITOR
            bool isPreview = false;
            isPreview = EditorSceneManager.IsPreviewSceneObject(camera);

            if (isPreview)
            {
                RendererLighting.SetPreviewShaderGlobals(cmd);
            }
            else
#endif
            RendererLighting.SetShapeLightShaderGlobals(cmd);

            context.ExecuteCommandBuffer(cmd);

            Profiler.BeginSample("RenderSpritesWithLighting - Prepare");
            DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
            DrawingSettings normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;
            Profiler.EndSample();

            for (int i = 0; i < s_SortingLayers.Length; i++)
            {
                // Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
                // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
                // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
                short layerValue = (short)s_SortingLayers[i].value;
                var   lowerBound = (i == 0) ? short.MinValue : layerValue;
                var   upperBound = (i == s_SortingLayers.Length - 1) ? short.MaxValue : layerValue;
                filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);

                int layerToRender = s_SortingLayers[i].id;

                Light2D.LightStats lightStats;
                lightStats = Light2D.GetLightStatsByLayer(layerToRender);

                if (lightStats.totalNormalMapUsage > 0)
                {
                    RendererLighting.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings);
                }

                cmd.Clear();
                if (lightStats.totalLights > 0)
                {
#if UNITY_EDITOR
                    cmd.name = "Render Lights - " + SortingLayer.IDToName(layerToRender);
#endif
                    RendererLighting.RenderLights(camera, cmd, layerToRender);
                }
                else
                {
                    RendererLighting.ClearDirtyLighting(cmd);
                }

                CoreUtils.SetRenderTarget(cmd, colorAttachment, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, ClearFlag.None, Color.white);
                context.ExecuteCommandBuffer(cmd);

                Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                Profiler.EndSample();

                if (lightStats.totalVolumetricUsage > 0)
                {
                    cmd.Clear();
#if UNITY_EDITOR
                    cmd.name = "Render Light Volumes" + SortingLayer.IDToName(layerToRender);
#endif
                    RendererLighting.RenderLightVolumes(camera, cmd, layerToRender);
                    context.ExecuteCommandBuffer(cmd);
                    cmd.Clear();
                }
            }

            cmd.Clear();
            Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
            RendererLighting.ReleaseRenderTextures(cmd);
            Profiler.EndSample();

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);

            filterSettings.sortingLayerRange = SortingLayerRange.all;
            RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
        }
Example #15
0
    void OnGUI()
    {
        var        currentPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
        GameObject obj = currentPrefabStage != null ? currentPrefabStage.prefabContentsRoot : Selection.activeGameObject;

        if (!obj)
        {
            EditorGUILayout.HelpBox(startGamePrefabInfo, MessageType.Info);
            return;
        }

        if (!EditorSceneManager.IsPreviewSceneObject(obj))
        {
            // это не режим редактирования префаба (т.е. либо asset, либо на сцене)
            bool isGamePrefab = obj.transform.root.gameObject.tag == "GamePrefab";

            if (isGamePrefab)
            {
                // это игровой префаб (либо asset, либо на сцене)
                if (PrefabUtility.IsPartOfPrefabAsset(obj) || PrefabUtility.IsPartOfPrefabInstance(obj))
                {
                    // проверяем, существует ли префаб ассет
                    string path = AssetDatabase.GetAssetPath(obj);

                    if (PrefabUtility.IsPartOfPrefabInstance(obj))
                    {
                        // этот префаб на сцене - находим его источник в ассетах (если он существует, т.к. редактировать надо именно его)
                        path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(obj);
                    }

                    if (!string.IsNullOrEmpty(path))
                    {
                        // юнити префаб для этого игрового префаба существует в ассетах, будем редактировать его
                        //obj = obj.transform.root.gameObject;
                        if (GUILayout.Button("Edit game prefab"))
                        {
                            FlushEditors();

                            // открываем префаб из ассетов на редактирование
                            Type t = typeof(UnityEditor.Experimental.SceneManagement.PrefabStageUtility);
                            System.Reflection.MethodInfo mi = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
                                                              .Single(m =>
                                                                      m.Name == "OpenPrefab" &&
                                                                      m.GetParameters().Length == 1 &&
                                                                      m.GetParameters()[0].ParameterType == typeof(string)
                                                                      );
                            mi.Invoke(null, new object[] { path });

                            UnityEditor.Experimental.SceneManagement.PrefabStage.prefabStageClosing -= OnSceneClosing;
                            UnityEditor.Experimental.SceneManagement.PrefabStage.prefabStageClosing += OnSceneClosing;
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("Selected object has no prefab asset file associated with it. Check if it should be a GamePrefab, and if it should - make proper Unity prefab out of this object.", MessageType.Warning);
                    }
                }
                else
                {
                    // этот игровой префаб не юнити префаб, т.е. связь разорвана была видимо
                    // можно предупредить об этом
                    EditorGUILayout.HelpBox("Selected object is GamePrefab, but not the Unity prefab. Check if GamePrefab tag on this object is requiered, and if it is - make proper Unity prefab out of this object.", MessageType.Warning);
                }
            }
            else
            {
                // этот объект - не игровой префаб, можно сделать его игровым префабом
                if (PrefabUtility.IsPartOfModelPrefab(obj))
                {
                    if (GUILayout.Button("Make Generic Game Prefab"))
                    {
                        MakePrefab(obj);
                    }

                    GUILayout.BeginHorizontal();
                    prefabName = GUILayout.TextField(prefabName);

                    if (GUILayout.Button("Make Cloth Game Prefab"))
                    {
                        string prefabPath = AssetDatabase.GetAssetPath(MakePrefab(obj));

                        GameObject prefabRoot = PrefabUtility.LoadPrefabContents(prefabPath);

                        // Создаем одежду - надо сначала проверить условия

                        // Скрываем риг, создаем pickup и item для него
                        GetRig(prefabRoot)?.SetActive(false);

                        prefabRoot.AddComponent <BoxCollider>();

                        var pickup = prefabRoot.AddComponent <ItemPickup>();
                        pickup.item      = PickupItemEditor.CreateItem(prefabRoot.name, prefabPath);
                        pickup.item.icon = GetDefaultIcon();

                        // радиус равен bounds сетки пополам
                        // fit collider позже

                        var equip = prefabRoot.AddComponent <Equippable>();
                        // hidden не ищем, т.к. риг скрыли уже
                        equip.equip = prefabRoot.GetComponentInChildren <SkinnedMeshRenderer>().gameObject.AddComponent <Equipmentizer>();
                        equip.equip.gameObject.SetActive(false);

                        var lying = prefabRoot.GetComponentsInChildren <Renderer>().First((x) => !x.GetComponent <Equipmentizer>());
                        if (lying)
                        {
                            pickup.worldView = lying.transform;
                        }

                        EquippableEditor.SetupEvents(equip);

                        ColliderFitter.FitCollider(prefabRoot, false);

                        var bounds = pickup.worldView.GetComponent <Renderer>().bounds;
                        if (bounds.extents.x > bounds.extents.z)
                        {
                            pickup.radius = bounds.extents.x;
                        }
                        else
                        {
                            pickup.radius = bounds.extents.z;
                        }

                        PrefabUtility.SaveAsPrefabAsset(prefabRoot, prefabPath);
                        PrefabUtility.UnloadPrefabContents(prefabRoot);
                    }

                    GUILayout.EndHorizontal();
                }
                else
                {
                    EditorGUILayout.HelpBox(startGamePrefabInfo, MessageType.Info);
                }
            }
        }
        else
        {
            // мы в режиме редактирования префаба - редактируем game prefab

            // rename game prefa (asset)
            GUILayout.BeginHorizontal();
            {
                obj.name = GUILayout.TextField(obj.name);
                string currentName = System.IO.Path.GetFileNameWithoutExtension(currentPrefabStage.prefabAssetPath);
                if (obj.name != currentName && GUILayout.Button("Apply", GUILayout.Width(150f)))
                {
                    AssetDatabase.RenameAsset(currentPrefabStage.prefabAssetPath, obj.name);
                }
            }
            GUILayout.EndHorizontal();

            // Body-rig - для персонажей и одежды
            var rig = GetRig(obj);
            if (rig && (GUILayout.Button(rig.activeSelf ? disableRigButton : enableRigButton)))
            {
                rig.SetActive(!rig.activeSelf);
            }

            // Компоненты игрового префаба, которые могут быть на нем
            GetForcedComponentEditor(obj, ref desc)?.OnInspectorGUI();
            GetComponentEditor(obj, "It is equippable", "It is not equippable", ref equip)?.OnInspectorGUI();
            GetComponentEditor(obj, "Can pick it up", "Can not pick that up", ref pickup)?.OnInspectorGUI();
        }
    }
Example #16
0
        public void LogStageInformation()
        {
#if UNITY_EDITOR
            // First check if input GameObject is persistent before checking what stage the GameObject is in
            if (EditorUtility.IsPersistent(gameObject))
            {
                if (!PrefabUtility.IsPartOfPrefabAsset(gameObject))
                {
                    LogConsole("The GameObject is a temporary object created during import. OnValidate() is called two times with a temporary object during import: First time is when saving cloned objects to .prefab file. Second event is when reading .prefab file objects during import");
                }
                else
                {
                    LogConsole("GameObject is part of an imported Prefab Asset (from the Library folder)");
                }
                return;
            }

            // If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it
            var mainStage    = StageUtility.GetMainStageHandle();
            var currentStage = StageUtility.GetStageHandle(gameObject);
            if (currentStage == mainStage)
            {
                if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                {
                    var type = PrefabUtility.GetPrefabAssetType(gameObject);
                    var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject));
                    LogConsole(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path));
                }
                else
                {
                    LogConsole("GameObject is a plain GameObject in the MainStage");
                }
            }
            else
            {
                var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject);
                if (prefabStage != null)
                {
                    if (PrefabUtility.IsPartOfPrefabInstance(gameObject))
                    {
                        var type             = PrefabUtility.GetPrefabAssetType(gameObject);
                        var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject));
                        LogConsole(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath));
                    }
                    else
                    {
                        var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath);
                        var type            = PrefabUtility.GetPrefabAssetType(prefabAssetRoot);
                        LogConsole(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath));
                    }
                }
                else if (EditorSceneManager.IsPreviewSceneObject(gameObject))
                {
                    LogConsole("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities.");
                }
                else
                {
                    LogConsole("Unknown GameObject Info");
                }
            }
#endif
        }
Example #17
0
        public static async void DoFieldType(ClassBind instance)
        {
            int affectCounts = 0;

            foreach (var _cb in instance.ScriptsToBind) //遍历
            {
                string   className = $"{_cb.Namespace}.{_cb.Class}";
                Assembly hotCode   = Assembly
                                     .LoadFile("Assets/HotUpdateResources/Dll/Hidden~/HotUpdateScripts.dll");
                Type t = hotCode.GetType(className); //加载热更类

                if (t == null)
                {
                    EditorUtility.DisplayDialog("ClassBind Error", $"Class {className} does not exist " +
                                                $"in hot update scripts solution!\n" +
                                                $"'{className}'类在热更工程中不存在", "OK");
                    return;
                }

                foreach (var field in _cb.Fields)
                {
                    var fieldType = t.GetField(field.fieldName,
                                               BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                               BindingFlags.Static)?.FieldType;
                    if (fieldType == null)
                    {
                        fieldType = t.GetProperty(field.fieldName,
                                                  BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                  BindingFlags.Static)?.PropertyType;
                    }

                    if (fieldType == null)
                    {
                        Log.PrintError($"{className}不存在{field.fieldName},已跳过");
                    }

                    SetType(field, fieldType, hotCode);
                    affectCounts++;

                    EditorUtility.DisplayProgressBar("ClassBind Progress",
                                                     $"Getting Field for {field.fieldName} {_cb.Fields.IndexOf(field)}/{_cb.Fields.Length}",
                                                     (float)_cb.Fields.IndexOf(field) / (float)_cb.Fields.Length);

                    await Task.Delay(50); //延迟一下,动画更丝滑
                }
            }

            EditorUtility.ClearProgressBar();

            //转换后保存场景
            bool saveResult = false;

            AssetDatabase.SaveAssets();
            bool isPreviewSceneObject = EditorSceneManager.IsPreviewSceneObject(Selection.activeGameObject);

            if (isPreviewSceneObject || PrefabUtility.IsPartOfAnyPrefab(instance.gameObject) || PrefabUtility.IsPartOfPrefabAsset(instance.gameObject))
            {
                PrefabUtility.SavePrefabAsset(instance.gameObject, out saveResult);
                EditorSceneManager.SaveOpenScenes();
            }
            else
            {
                var scene = EditorSceneManager.GetActiveScene();
                saveResult = EditorSceneManager.SaveScene(scene, scene.path);
            }

            string result   = saveResult ? "succeeded" : "failed";
            string resultZh = saveResult ? "成功" : "失败";

            EditorUtility.ClearProgressBar();
            EditorUtility.DisplayDialog("ClassBind Result",
                                        $"Set {affectCounts} fieldTypes into ClassBind: {instance.name} and saved the scene {result}\n" +
                                        $"ClassBind: {instance.name}中{affectCounts}个fields已自动设置FieldType,且保存{resultZh}",
                                        "Done");
        }