예제 #1
0
 public override void OnInspectorGUI()
 {
     base.OnInspectorGUI();
     serializedObject.Update();
     stateMaskProperty.intValue = (int)(EGameState)EditorGUILayout.EnumMaskPopup("Active states", (EGameState)stateMaskProperty.intValue);
     serializedObject.ApplyModifiedProperties();
 }
예제 #2
0
    public override void OnInspectorGUI()
    {
        BPhysicsWorld pw = (BPhysicsWorld)target;

        pw.DoDebugDraw   = EditorGUILayout.Toggle(gcDoDebugDraw, pw.DoDebugDraw);
        pw.DebugDrawMode = (BulletSharp.DebugDrawModes)EditorGUILayout.EnumMaskPopup(DebugDrawMode, pw.DebugDrawMode);

        pw.worldType = (BPhysicsWorld.WorldType)EditorGUILayout.EnumPopup("World Type", pw.worldType);
        EditorGUILayout.Separator();
        pw.gravity = EditorGUILayout.Vector3Field("Gravity", pw.gravity);
        EditorGUILayout.Separator();

        pw.collisionType = (BPhysicsWorld.CollisionConfType)EditorGUILayout.EnumPopup("Collision Type", pw.collisionType);


        pw.broadphaseType          = (BPhysicsWorld.BroadphaseType)EditorGUILayout.EnumPopup("Broadphase Algorithm", pw.broadphaseType);
        pw.axis3SweepBroadphaseMin = EditorGUILayout.Vector3Field("Broadphase Axis 3 Sweep Min", pw.axis3SweepBroadphaseMin);
        pw.axis3SweepBroadphaseMax = EditorGUILayout.Vector3Field("Broadphase Axis 3 Sweep Max", pw.axis3SweepBroadphaseMax);

        pw.debugType = EditorInterface.DrawDebug(pw.debugType, pw);

        if (GUI.changed)
        {
            EditorUtility.SetDirty(pw);
            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
            Undo.RecordObject(pw, "Undo Physics World");
        }
    }
    private void DrawEnemyThreshold(int idx)
    {
        //EditorGUILayout.BeginVertical();
        // Activation Day
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical();
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Activation Day:");
        qParamTarget.enemyThresholds[idx].DayMarker = EditorGUILayout.IntField(qParamTarget.enemyThresholds[idx].DayMarker);
        EditorGUILayout.EndHorizontal();

        //// Activation Rep
        //EditorGUILayout.BeginHorizontal();
        //EditorGUILayout.PrefixLabel("Activation Rep:");
        //qParamTarget.enemyThresholds[idx].RepMarker = EditorGUILayout.IntField(qParamTarget.enemyThresholds[idx].RepMarker);
        //EditorGUILayout.EndHorizontal();

        // Type and button
        qParamTarget.enemyThresholds[idx].AvailableEnemies = (EnemyTypes)EditorGUILayout.EnumMaskPopup(new GUIContent(), qParamTarget.enemyThresholds[idx].AvailableEnemies);
        EditorGUILayout.EndVertical();
        if (GUILayout.Button("-"))
        {
            qParamTarget.enemyThresholds.RemoveAt(idx);
        }
        EditorGUILayout.EndHorizontal();

        //EditorGUILayout.EndVertical();
    }
예제 #4
0
 protected override bool DrawWizardGUI()
 {
     EditorGUILayout.LabelField(new GUIContent("Stash Message:"));
     stashMessage   = EditorGUILayout.TextArea(stashMessage, GUILayout.Height(EditorGUIUtility.singleLineHeight * 6));
     stashModifiers = (StashModifiers)EditorGUILayout.EnumMaskPopup("Stash Modifiers", stashModifiers);
     return(false);
 }
예제 #5
0
    void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.BeginVertical();
        tex0       = (Texture2D)EditorGUILayout.ObjectField(tex0, typeof(Texture2D), false);
        tex0invert = EditorGUILayout.Toggle("Invert", tex0invert);
        tex0r      = (Channel)EditorGUILayout.EnumMaskPopup("R channel map", tex0r);
        tex0g      = (Channel)EditorGUILayout.EnumMaskPopup("G channel map", tex0g);
        tex0b      = (Channel)EditorGUILayout.EnumMaskPopup("B channel map", tex0b);
        tex0a      = (Channel)EditorGUILayout.EnumMaskPopup("A channel map", tex0a);
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        EditorGUILayout.BeginVertical();
        tex1       = (Texture2D)EditorGUILayout.ObjectField(tex1, typeof(Texture2D), false);
        tex1invert = EditorGUILayout.Toggle("Invert", tex1invert);
        tex1r      = (Channel)EditorGUILayout.EnumMaskPopup("R channel map", tex1r);
        tex1g      = (Channel)EditorGUILayout.EnumMaskPopup("G channel map", tex1g);
        tex1b      = (Channel)EditorGUILayout.EnumMaskPopup("B channel map", tex1b);
        tex1a      = (Channel)EditorGUILayout.EnumMaskPopup("A channel map", tex1a);
        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space();

        if (GUILayout.Button("Create"))
        {
            Create();
            Close();
        }
    }
예제 #6
0
        void OnGUI()
        {
            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            if (string.IsNullOrEmpty(m_bundlePath))
            {
                m_bundlePath = EditorUserBuildSettings.GetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath");
            }
            var bp = GUILayout.TextField(m_bundlePath);

            if (bp != m_bundlePath)
            {
                EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_bundlePath = bp);
            }
            if (GUILayout.Button("Browse"))
            {
                BrowseForFolder();
            }
            GUILayout.EndHorizontal();

            m_ForceRebuild = GUILayout.Toggle(m_ForceRebuild, "Force Rebuild/Clear Bundle Folder");
            m_buildTarget  = (BuildTarget)EditorGUILayout.EnumPopup("Target", m_buildTarget);
            m_options      = (BuildAssetBundleOptions)EditorGUILayout.EnumMaskPopup("Options", m_options);

            if (GUILayout.Button("Build"))
            {
                if (string.IsNullOrEmpty(m_bundlePath))
                {
                    BrowseForFolder();
                }

                if (m_ForceRebuild)
                {
                    if (EditorUtility.DisplayDialog("File delete confirmation", "Do you want to delete all files in the directory " + m_bundlePath + "?", "Yes", "No"))
                    {
                        try
                        {
                            if (Directory.Exists(m_bundlePath))
                            {
                                Directory.Delete(m_bundlePath, true);
                            }
                        }
                        catch (System.Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                }
                if (!Directory.Exists(m_bundlePath))
                {
                    Directory.CreateDirectory(m_bundlePath);
                }
                BuildPipeline.BuildAssetBundles(m_bundlePath, m_options, m_buildTarget);
                AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
                // m_showSummary = true;
            }
            GUILayout.EndVertical();
        }
예제 #7
0
        void OnGUI()
        {
            GUILayout.Space(5);

            if (buildingEditor == null) // close the window if we dont have a reference to our building editor window, can happens due to unity compiling scripts.
            {
                Close();
            }

            GUILayout.BeginVertical("Property Creator Editor Window", boxStyle);

            GUILayout.Space(20);

            propertyName   = EditorGUILayout.TextField(new GUIContent("Name :", "What is the name of this property ?, can be used for knowing what that property is being used for."), propertyName);
            positionAnchor = (SocketPositionAnchor)EditorGUILayout.EnumPopup(new GUIContent("Starting Position Anchor :", "Where will it spawn the object in the building local position ? use this to help you position your property faster, it doesnt influence any further features."), positionAnchor);

            if (creatingType == ModifierType.Socket)
            {
                previewGameObject = (GameObject)EditorGUILayout.ObjectField(new GUIContent("Socket Gizmos Preview GameObject :", "This GameObject will be used for preview on gizmos, it will grab the parameters from it into the collider to hlep you easily get your scale right."), previewGameObject, typeof(GameObject), false);
                receivesBuildings = (BuildingType)EditorGUILayout.EnumMaskPopup(new GUIContent("Receive Buildings :", "What building will be snapped into this socket ?"), receivesBuildings);
                socketPlacingType = (PlacingRestrictionType)EditorGUILayout.EnumMaskPopup(new GUIContent("Placing Type :", "What the placing method will be on this socket ?"), socketPlacingType);
            }
            else if (creatingType == ModifierType.Condition)
            {
                condition = EditorGUILayout.ObjectField(new GUIContent("Condition Script :", "What condition script will this condition use ? you can always edit it later. if you leave this blank it will use the BaseCondition script. "), condition, typeof(MonoScript), false) as MonoScript;

                if (condition != null && !condition.GetClass().BaseType.Equals(typeof(BaseCondition))) // reset condition if its type isnt what we need ( a condition ).
                {
                    condition = null;
                }
            }
            else // snap points
            {
                targetType = (BuildingType)EditorGUILayout.EnumMaskField("Target type :", targetType);
            }

            if (GUILayout.Button("Create " + creatingType.ToString()))
            {
                if (creatingType == ModifierType.Socket)
                {
                    buildingEditor.script.CreateSocket(propertyName, positionAnchor, previewGameObject, receivesBuildings, socketPlacingType);
                }
                else if (creatingType == ModifierType.Condition)
                {
                    buildingEditor.script.CreateCondition(propertyName, positionAnchor, condition == null ? typeof(BaseCondition) : condition.GetClass());
                }
                else if (creatingType == ModifierType.SnapPoint)
                {
                    buildingEditor.script.CreateSnapPoint(propertyName, positionAnchor, targetType);
                }

                Close();
            }
            else
            {
                EditorGUILayout.EndVertical();
            }
        }
예제 #8
0
        private void OnGUI()
        {
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Bundle Folder: ", GUILayout.MaxWidth(100));
                EditorPrefs.SetString("SimpleBundlerBundleDir", EditorGUILayout.TextField(EditorPrefs.GetString("SimpleBundlerBundleDir", defaultAssetBundleDirectory)));
                if (GUILayout.Button("...", GUILayout.Width(30)))
                {
                    EditorPrefs.SetString("SimpleBundlerBundleDir", (EditorUtility.OpenFolderPanel("Select an Asset Bundle Directory", EditorPrefs.GetString("SimpleBundlerBundleDir", defaultAssetBundleDirectory), "").Remove(0, Directory.GetCurrentDirectory().Length + 1)));
                }
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Output Folder: ", GUILayout.MaxWidth(100));
                EditorPrefs.SetString("SimpleBundlerOutputDir", EditorGUILayout.TextField(EditorPrefs.GetString("SimpleBundlerOutputDir", defaultOutputDirectory)));
                if (GUILayout.Button("...", GUILayout.Width(30)))
                {
                    EditorPrefs.SetString("SimpleBundlerOutputDir", (EditorUtility.OpenFolderPanel("Select an Output Directory", EditorPrefs.GetString("SimpleBundlerOutputDir", defaultAssetBundleDirectory), "").Remove(0, Directory.GetCurrentDirectory().Length + 1)));
                }
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Clear Output Folder on Build:", GUILayout.MaxWidth(200));
                EditorPrefs.SetBool("SimpleBundlerClearOnBuild", EditorGUILayout.Toggle(EditorPrefs.GetBool("SimpleBundlerClearOnBuild", true)));
            }
            EditorGUILayout.EndHorizontal();

            buildOptions = (BuildAssetBundleOptions)EditorGUILayout.EnumMaskPopup("Build Options: ", buildOptions);

            if (GUILayout.Button("Build AssetBundles"))
            {
                var buildInfo = BuildAllAssetBundles(buildOptions);
                cachedInfo = new List <CachedBuildInfo>();
                for (var i = 0; i < buildInfo.Count; i++)
                {
                    var info = new CachedBuildInfo();
                    info.BundlePaths = new List <string>();
                    info.LocalPaths  = new List <string>();
                    info.BuildName   = buildInfo[i].assetBundleName;
                    info.Variant     = buildInfo[i].assetBundleVariant;
                    for (var j = 0; j < buildInfo[i].addressableNames.Length; j++)
                    {
                        info.BundlePaths.Add(buildInfo[i].addressableNames[j]);
                        info.LocalPaths.Add(buildInfo[i].assetNames[j]);
                    }
                    cachedInfo.Add(info);
                }
            }

            DisplayResults();
        }
        public void OnGUI(Rect pos)
        {
            //options
            EditorGUILayout.Space();
            GUILayout.BeginVertical();
            m_buildTarget     = (ValidBuildTarget)EditorGUILayout.EnumPopup("Target", m_buildTarget);
            m_options         = (BuildAssetBundleOptions)EditorGUILayout.EnumMaskPopup("Options", m_options);
            m_ForceRebuild    = GUILayout.Toggle(m_ForceRebuild, "Clear all build folders on build");
            m_CopyToStreaming = GUILayout.Toggle(m_CopyToStreaming, "Copy bundles to " + m_streamingPath);


            //output path
            EditorGUILayout.Space();
            m_UseDefaultPath = GUILayout.Toggle(m_UseDefaultPath, "Use default output directory.");
            GUILayout.BeginHorizontal();
            if (string.IsNullOrEmpty(m_outputPath))
            {
                m_outputPath = EditorUserBuildSettings.GetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath");
            }

            var origPath = m_outputPath;

            if (m_UseDefaultPath)
            {
                m_outputPath  = "AssetBundles/";
                m_outputPath += m_buildTarget.ToString();
                GUILayout.Label("Output Directory:  ");
                GUILayout.Label(m_outputPath);
            }
            else
            {
                GUILayout.Label("Output Directory:  ");
                m_outputPath = GUILayout.TextArea(m_outputPath);
            }
            if (m_outputPath != origPath)
            {
                EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_outputPath);
            }
            GUILayout.EndHorizontal();
            EditorGUILayout.Space();



            // build.
            EditorGUILayout.Space();
            if (GUILayout.Button("Build"))
            {
                ExecuteBuild();
            }
            GUILayout.EndVertical();
        }
예제 #10
0
        void OnGUI()
        {
            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            m_bundlePath = GUILayout.TextField(m_bundlePath);
            if (GUILayout.Button("Browse"))
            {
                BrowseForFolder();
            }
            GUILayout.EndHorizontal();

            m_ForceRebuild = GUILayout.Toggle(m_ForceRebuild, "Force Rebuild/Clear Bundle Folder");
            m_buildTarget  = (BuildTarget)EditorGUILayout.EnumPopup("Target", m_buildTarget);
            m_options      = (BuildAssetBundleOptions)EditorGUILayout.EnumMaskPopup("Options", m_options);

            if (GUILayout.Button("Build"))
            {
                if (string.IsNullOrEmpty(m_bundlePath))
                {
                    BrowseForFolder();
                }

                if (!Directory.Exists(m_bundlePath))
                {
                    Debug.Log("Invalid bundle path " + m_bundlePath);
                }
                else
                {
                    if (m_ForceRebuild)
                    {
                        if (EditorUtility.DisplayDialog("File delete confirmation", "Do you want to delete all files in the directory " + m_bundlePath + "?", "Yes", "No"))
                        {
                            Directory.Delete(m_bundlePath, true);
                            Directory.CreateDirectory(m_bundlePath);
                        }
                    }
                    BuildPipeline.BuildAssetBundles(m_bundlePath, BuildAssetBundleOptions.None, m_buildTarget);
                    AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
                    m_showSummary = true;
                }
            }
            GUILayout.EndVertical();
        }
    private void DrawDifficultyDefinition(int idx)
    {
        if (qParamTarget.difficultyDefinitions[idx] == null)
        {
            qParamTarget.difficultyDefinitions[idx] = new DifficultyDefinition();
        }

        var newDefinition = qParamTarget.difficultyDefinitions[idx];

        diffDefIsToggled[idx] = EditorGUILayout.Foldout(
            diffDefIsToggled[idx],
            string.Format("Difficulty Definition ({0})", DifficultyFromInt(idx))
            );

        if (diffDefIsToggled[idx])
        {
            EditorGUI.indentLevel++;
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Min/Max Non-suicide:");
            newDefinition.minNonSuicide = EditorGUILayout.IntField(newDefinition.minNonSuicide);
            newDefinition.maxNonSuicide = EditorGUILayout.IntField(newDefinition.maxNonSuicide);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Min/Max Suicide:");
            newDefinition.minSuicide = EditorGUILayout.IntField(newDefinition.minSuicide);
            newDefinition.maxSuicide = EditorGUILayout.IntField(newDefinition.maxSuicide);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Min/Max Friendlies (Obsolete):");
            newDefinition.minFriendlies = EditorGUILayout.IntField(newDefinition.minFriendlies);
            newDefinition.maxFriendlies = EditorGUILayout.IntField(newDefinition.maxFriendlies);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("House Status:");
            newDefinition.houseStatus = (HouseStatus)EditorGUILayout.EnumMaskPopup(new GUIContent(), newDefinition.houseStatus);
            EditorGUILayout.EndHorizontal();
            EditorGUI.indentLevel--;
        }
    }
예제 #12
0
        public override void DrawFeatureGUI(Material mat)
        {
            detailNoise       = EditorGUILayout.Toggle(CDetailNoise, detailNoise);
            distanceNoise     = EditorGUILayout.Toggle(CDistanceNoise, distanceNoise);
            noiseChannelCount = (NormalNoiseChannels)EditorGUILayout.EnumPopup(CNormalNoise, noiseChannelCount);

#if __MICROSPLAT_TRIPLANAR__
            if (detailNoise || distanceNoise || noiseChannelCount != NormalNoiseChannels.Off)
            {
                EditorGUI.indentLevel++;
                antiTileTriplanar = EditorGUILayout.Toggle(CTriplanarControls, antiTileTriplanar);
                EditorGUI.indentLevel--;
            }
#endif

            distanceResample = (DistanceResampleMode)EditorGUILayout.EnumPopup(CDistanceResample, distanceResample);
#if __MICROSPLAT_TEXTURECLUSTERS__
            if (distanceResample != DistanceResampleMode.None)
            {
                EditorGUI.indentLevel++;
                resampleClusters = EditorGUILayout.Toggle(CResampleClusters, resampleClusters);
                EditorGUI.indentLevel--;
            }
#endif

            if (distanceResample != DistanceResampleMode.None)
            {
                EditorGUI.indentLevel++;
                distanceResampleHeightBlend = EditorGUILayout.Toggle(CDistanceResampleHeightBlend, distanceResampleHeightBlend);
                distanceResampleFade        = (DistanceResampleFade)EditorGUILayout.EnumPopup(CDistanceResampleFade, distanceResampleFade);
                EditorGUI.indentLevel--;
            }

#if UNITY_2017_3_OR_NEWER
            antiTileOptions = (AntiTileOptions)EditorGUILayout.EnumFlagsField(CAntiTileOptions, antiTileOptions);
#else
            antiTileOptions = (AntiTileOptions)EditorGUILayout.EnumMaskPopup(CAntiTileOptions, antiTileOptions);
#endif
        }
    public void BakingGUI(MicroSplatTerrain t)
    {
        if (needsBake && Event.current.type == EventType.Repaint)
        {
            needsBake = false;
            Bake(t);
        }
        if (MicroSplatUtilities.DrawRollup("Render Baking", false))
        {
            res = (BakingResolutions)EditorGUILayout.EnumPopup(new GUIContent("Resolution"), res);

         #if UNITY_2017_3_OR_NEWER
            passes = (BakingPasses)EditorGUILayout.EnumFlagsField(new GUIContent("Features"), passes);
         #else
            passes = (BakingPasses)EditorGUILayout.EnumMaskPopup(new GUIContent("Features"), passes);
         #endif

            if (GUILayout.Button("Export Selected"))
            {
                needsBake = true;
            }
        }
    }
예제 #14
0
        protected override void RenderContent(UnityEngine.Object undoRecordObject)
        {
            int newInt; string newString; bool newBool;

            var content = new GUIContent();

            content.text    = "Object types";
            content.tooltip = "The types of objects that can participate in the conversion operation. Applies to both scene objects and prefabs.";
            newInt          = (int)((GameObjectType)EditorGUILayout.EnumMaskPopup(content, (GameObjectType)_convertableObjectTypes));
            if (newInt != (int)_convertableObjectTypes)
            {
                EditorUndoEx.Record(undoRecordObject);
                _convertableObjectTypes = (GameObjectType)newInt;
            }

            content.text    = "Prefab folder";
            content.tooltip = "Allows you to specify a folder which contains prefabs that need to be converted. You can either write the path manually or " +
                              "simply drag and drop a folder onto the text field to have the path automatically extracted for you.";
            newString = EditorGUILayout.TextField(content, PrefabFolder);
            if (newString != PrefabFolder)
            {
                EditorUndoEx.Record(undoRecordObject);
                PrefabFolder = newString;
            }
            _prefabFolderDropRect = GUILayoutUtility.GetLastRect();

            content.text    = "Process prefab subfolders";
            content.tooltip = "If this is checked, the conversion utility will also convert prefabs which reside in any subfolders that reside in the specified folder. Otherwise, " +
                              "subfolders are ignored.";
            newBool = EditorGUILayout.ToggleLeft(content, ProcessPrefabSubfolders);
            if (newBool != ProcessPrefabSubfolders)
            {
                EditorUndoEx.Record(undoRecordObject);
                ProcessPrefabSubfolders = newBool;
            }
        }
예제 #15
0
        private static void Preferences()
        {
            using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope())
            {
                EditorGUILayout.LabelField("All", EditorStyles.helpBox);
                                #if UNITY_2017_3_OR_NEWER
                zoomToCursor = (ZoomToCursor)EditorGUILayout.EnumFlagsField("Zoom To Cursor", zoomToCursor);
                                #else
                zoomToCursor = (ZoomToCursor)EditorGUILayout.EnumMaskPopup("Zoom To Cursor", zoomToCursor);
                                #endif
                if (changeCheckScope.changed)
                {
                    EditorPrefs.SetInt("vertxCameraZoomToCursor", (int)zoomToCursor);
                }
            }

            using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope())
            {
                zoomToCursorIgnoresBackfaces = EditorGUILayout.Toggle("Zoom To Cursor Ignores Backfaces", zoomToCursorIgnoresBackfaces);

                if (changeCheckScope.changed)
                {
                    EditorPrefs.SetBool("vertxZoomToCursorIgnoresBackfaces", zoomToCursorIgnoresBackfaces);
                }
            }

            using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope())
            {
                EditorGUILayout.LabelField("Six Axis", EditorStyles.helpBox);
                alignCameraAutomatically = EditorGUILayout.Toggle("Align Camera Automatically", alignCameraAutomatically);
                if (changeCheckScope.changed)
                {
                    EditorPrefs.SetBool("vertxAlignCameraAutomatically", alignCameraAutomatically);
                }
            }
        }
예제 #16
0
        public override void OnInspectorGUI()
        {
            //return;

            //base.OnInspectorGUI();
            apPortrait targetPortrait = target as apPortrait;

            if (targetPortrait != _targetPortrait)
            {
                _targetPortrait = targetPortrait;
                Init();
            }
            if (_targetPortrait == null)
            {
                //Profiler.EndSample();
                return;
            }

            //Profiler.BeginSample("anyPortrait Inspector GUI");


            //return;
            if (apEditor.IsOpen())
            {
                //에디터가 작동중에는 안보이도록 하자
                EditorGUILayout.LabelField("Editor is opened");

                //Profiler.EndSample();

                return;
            }

            try
            {
                bool          prevImportant         = _targetPortrait._isImportant;
                MonoBehaviour prevAnimEventListener = _targetPortrait._optAnimEventListener;
                int           prevSortingLayerID    = _targetPortrait._sortingLayerID;
                int           prevSortingOrder      = _targetPortrait._sortingOrder;

                _targetPortrait._isImportant          = EditorGUILayout.Toggle("Is Important", _targetPortrait._isImportant);
                _targetPortrait._optAnimEventListener = (MonoBehaviour)EditorGUILayout.ObjectField("Event Listener", _targetPortrait._optAnimEventListener, typeof(MonoBehaviour), true);


                GUILayout.Space(5);
                //추가3.22
                //Sorting Layer
                string[] sortingLayerName = new string[SortingLayer.layers.Length];
                int      layerIndex       = -1;
                for (int i = 0; i < SortingLayer.layers.Length; i++)
                {
                    sortingLayerName[i] = SortingLayer.layers[i].name;
                    if (SortingLayer.layers[i].id == _targetPortrait._sortingLayerID)
                    {
                        layerIndex = i;
                    }
                }
                int nextLayerIndex = EditorGUILayout.Popup("Sorting Layer", layerIndex, sortingLayerName);
                int nextLayerOrder = EditorGUILayout.IntField("Sorting Order", _targetPortrait._sortingOrder);

                if (nextLayerIndex != layerIndex)
                {
                    //Sorting Layer를 바꾸자
                    if (nextLayerIndex >= 0 && nextLayerIndex < SortingLayer.layers.Length)
                    {
                        string nextLayerName = SortingLayer.layers[nextLayerIndex].name;
                        _targetPortrait.SetSortingLayer(nextLayerName);
                    }
                }
                if (nextLayerOrder != _targetPortrait._sortingOrder)
                {
                    _targetPortrait.SetSortingOrder(nextLayerOrder);
                }


                if (prevImportant != _targetPortrait._isImportant ||
                    prevAnimEventListener != _targetPortrait._optAnimEventListener ||
                    prevSortingLayerID != _targetPortrait._sortingLayerID ||
                    prevSortingOrder != _targetPortrait._sortingOrder)
                {
                    apEditorUtil.SetEditorDirty();
                }

                GUILayout.Space(5);

                _isFold_RootPortraits = EditorGUILayout.Foldout(_isFold_RootPortraits, "Root Portraits");
                if (_isFold_RootPortraits)
                {
                    string strRootPortrait = "";
                    if (_targetPortrait._optRootUnitList.Count == 0)
                    {
                        strRootPortrait = "No Baked Portrait";
                    }
                    else if (_targetPortrait._optRootUnitList.Count == 1)
                    {
                        strRootPortrait = "1 Baked Portrait";
                    }
                    else
                    {
                        strRootPortrait = _targetPortrait._optRootUnitList.Count + " Baked Portraits";
                    }
                    EditorGUILayout.LabelField(strRootPortrait);
                    GUILayout.Space(5);
                    for (int i = 0; i < _targetPortrait._optRootUnitList.Count; i++)
                    {
                        apOptRootUnit rootUnit = _targetPortrait._optRootUnitList[i];
                        EditorGUILayout.ObjectField("[" + i + "]", rootUnit, typeof(apOptRootUnit), true);
                    }

                    GUILayout.Space(20);
                }



                _isFold_AnimationClips = EditorGUILayout.Foldout(_isFold_AnimationClips, "Animation Clips");
                if (_isFold_AnimationClips)
                {
                    string strAnimClips = "";
                    if (_targetPortrait._animClips.Count == 0)
                    {
                        strAnimClips = "No Animation Clip";
                    }
                    else if (_targetPortrait._animClips.Count == 1)
                    {
                        strAnimClips = "1 Animation Clip";
                    }
                    else
                    {
                        strAnimClips = _targetPortrait._animClips.Count + " Animation Clips";
                    }
                    EditorGUILayout.LabelField(strAnimClips);
                    GUILayout.Space(5);
                    for (int i = 0; i < _targetPortrait._animClips.Count; i++)
                    {
                        apAnimClip animClip = _targetPortrait._animClips[i];
                        if (animClip._uniqueID == _targetPortrait._autoPlayAnimClipID)
                        {
                            EditorGUILayout.TextField("[" + i + "] (Auto Play)", animClip._name);
                        }
                        else
                        {
                            EditorGUILayout.TextField("[" + i + "]", animClip._name);
                        }
                    }

                    GUILayout.Space(20);
                }


                bool isChanged = false;

                _isFold_ConrolParameters = EditorGUILayout.Foldout(_isFold_ConrolParameters, "Control Parameters");
                if (_isFold_ConrolParameters)
                {
#if UNITY_2017_3_OR_NEWER
                    _curControlCategory = (apControlParam.CATEGORY)EditorGUILayout.EnumFlagsField(new GUIContent("Category"), _curControlCategory);
#else
                    _curControlCategory = (apControlParam.CATEGORY)EditorGUILayout.EnumMaskPopup(new GUIContent("Category"), _curControlCategory);
#endif

                    EditorGUILayout.Space();
                    //1. 컨르롤러를 제어할 수 있도록 하자

                    if (_controlParams != null)
                    {
                        for (int i = 0; i < _controlParams.Count; i++)
                        {
                            if ((int)(_controlParams[i]._category & _curControlCategory) != 0)
                            {
                                if (GUI_ControlParam(_controlParams[i]))
                                {
                                    isChanged = true;
                                }
                            }
                        }
                    }

                    GUILayout.Space(20);
                }


                GUILayout.Space(10);

                //2. 토글 버튼을 두어서 기본 Inspector 출력 여부를 결정하자.
                string strBaseButton = "Show All Properties";
                if (_showBaseInspector)
                {
                    strBaseButton = "Hide Properties";
                }

                if (GUILayout.Button(strBaseButton, GUILayout.Height(20)))
                {
                    _showBaseInspector = !_showBaseInspector;
                }

                if (_showBaseInspector)
                {
                    base.OnInspectorGUI();
                }


                if (!Application.isPlaying && isChanged)
                {
                    //플레이 중이라면 자동으로 업데이트 될 것이다.
                    _targetPortrait.UpdateForce();
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("apInspector_Portrait Exception : " + ex);
            }

            //Profiler.EndSample();
        }
예제 #17
0
        private void OnGUI()
        {
            //Unable to use a named GUIStyle without a current skin.
            //Most likely you need to move your GUIStyle initialization code to OnGUI
            //GUI风格元素需要在OnGUI方法里初始化,否则会报以上错误,界面也会发生显示错误
            if (checkStyle == null)
            {
                checkStyle = new CheckStyle();
            }

            GUILayout.BeginHorizontal(checkStyle.ToolBar, new GUILayoutOption[] { GUILayout.Width(this.position.width) });
            {
                EditorGUI.BeginChangeCheck();

                checkTypeMix = (CheckEnumType)EditorGUILayout.EnumMaskPopup(new GUIContent(titleStr), checkTypeMix, checkStyle.TE_ToolBarBtn, new GUILayoutOption[] { GUILayout.Width(600) });

                if (EditorGUI.EndChangeCheck())
                {
                    //检查类型分类
                    OnCheckTypeSelect(checkTypeMix);
                }

                EditorGUI.BeginChangeCheck();

                if (GUILayout.Button(string.Format("当前目录{0}", filePath), checkStyle.TE_ToolBarBtn))
                {
                    filePath = EditorUtility.OpenFolderPanel("选择筛选目录{0}", Application.dataPath, string.Empty);

                    var currentDir = BuildUtils.GetUnityPath(Path.GetFullPath(Directory.GetCurrentDirectory()));

                    filePath = filePath.Replace(string.Format("{0}/", currentDir), "");
                }
                if (EditorGUI.EndChangeCheck())
                {
                    checkManager.SetFilePath(filePath);

                    Debug.Log(string.Format("当前选择目录:{0}", filePath));
                }
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("Check"))
                {
                    //检查
                    if (checkManager.GetPathListByFilePath())
                    {
                        checkManager.OnCheck();
                    }
                }

                if (GUILayout.Button("Format"))
                {
                    //处理
                    checkManager.OnFormat();
                }
            }
            GUILayout.EndHorizontal();

            #region 表格GUI绘制
            //表格 GUI 绘制
            Rect viewRect = new Rect(border * 2 + this.position.width * percet, offset * 2, this.position.width * (1 - percet) - border * 3, this.position.height - offset * 2 - border);

            if (table != null)
            {
                table.Draw(viewRect);
            }
            #endregion

            #region 检查项GUI绘制

            //检查项 itemlist 绘制
            Rect itemViewRect = new Rect(border, offset * 2, this.position.width * percet, this.position.height - offset * 2 - border);

            GUILayout.BeginArea(itemViewRect, checkStyle.WindowBackground);

            scrollview = GUILayout.BeginScrollView(scrollview, GUIStyle.none, GUI.skin.verticalScrollbar);

            DrawItemWind(itemViewRect);

            GUILayout.EndScrollView();

            GUILayout.EndArea();

            #endregion
        }
        public override void OnInspectorGUI()
        {
            //return;

            //base.OnInspectorGUI();
            apPortrait targetPortrait = target as apPortrait;

            if (targetPortrait != _targetPortrait)
            {
                _targetPortrait = targetPortrait;
                Init();
            }
            if (_targetPortrait == null)
            {
                //Profiler.EndSample();
                return;
            }

            Profiler.BeginSample("anyPortrait Inspector GUI");


            //return;
            if (apEditor.IsOpen())
            {
                //에디터가 작동중에는 안보이도록 하자
                EditorGUILayout.LabelField("Editor is opened");

                Profiler.EndSample();

                return;
            }

            try
            {
                EditorGUILayout.LabelField("Control Parameters");
                _curControlCategory = (apControlParam.CATEGORY)EditorGUILayout.EnumMaskPopup(new GUIContent("Category"), _curControlCategory);

                EditorGUILayout.Space();
                //1. 컨르롤러를 제어할 수 있도록 하자
                bool isChanged = false;
                if (_controlParams != null)
                {
                    for (int i = 0; i < _controlParams.Count; i++)
                    {
                        if ((int)(_controlParams[i]._category & _curControlCategory) != 0)
                        {
                            if (GUI_ControlParam(_controlParams[i]))
                            {
                                isChanged = true;
                            }
                        }
                    }
                }

                GUILayout.Space(30);

                //2. 토글 버튼을 두어서 기본 Inspector 출력 여부를 결정하자.
                string strBaseButton = "Show All Properties";
                if (_showBaseInspector)
                {
                    strBaseButton = "Hide Properties";
                }

                if (GUILayout.Button(strBaseButton, GUILayout.Height(20)))
                {
                    _showBaseInspector = !_showBaseInspector;
                }

                if (_showBaseInspector)
                {
                    base.OnInspectorGUI();
                }


                if (!Application.isPlaying && isChanged)
                {
                    //플레이 중이라면 자동으로 업데이트 될 것이다.
                    _targetPortrait.UpdateForce();
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("apInspector_Portrait Exception : " + ex);
            }

            Profiler.EndSample();
        }
        ///Draws an Editor field for object of type directly
        public static object DrawEditorFieldDirect(GUIContent content, object value, Type t, FieldInfo field = null, object context = null, object[] attributes = null)
        {
            if (typeof(UnityObject).IsAssignableFrom(t) == false && t != typeof(Type))
            {
                //Check abstract
                if ((value != null && value.GetType().IsAbstract) || (value == null && t.IsAbstract))
                {
                    EditorGUILayout.LabelField(content, new GUIContent(string.Format("Abstract ({0})", t.FriendlyName())));
                    return(value);
                }

                if (t != typeof(object) && !t.IsAbstract && !t.IsInterface)
                {
                    if (t.GetConstructor(Type.EmptyTypes) != null || t.IsArray || t.RTIsValueType())
                    {
                        if (value == null)
                        {
                            GUILayout.BeginHorizontal();
                            EditorGUILayout.PrefixLabel(content, (GUIStyle)"button");
                            if (GUILayout.Button("(null) Create", GUILayout.Height(16)))
                            {
                                if (t.IsArray)
                                {
                                    value = Array.CreateInstance(t.GetElementType(), 0);
                                }
                                else
                                {
                                    value = Activator.CreateInstance(t);
                                }
                            }
                            GUILayout.EndHorizontal();
                            return(value);
                        }
                    }
                }

                // //Auto create instance for some types
                // if ( value == null && t != typeof(object) && !t.IsAbstract && !t.IsInterface ) {
                //     if ( t.GetConstructor(Type.EmptyTypes) != null || t.IsArray || t.RTIsValueType() ) {
                //         if ( t.IsArray ) { value = Array.CreateInstance(t.GetElementType(), 0); } else { value = Activator.CreateInstance(t); }
                //     }
                // }
            }

            //Check the type
            if (typeof(UnityObject).IsAssignableFrom(t))
            {
                if (t == typeof(Component) && (value is Component))
                {
                    return(ComponentField(content, (Component)value, typeof(Component)));
                }
                return(EditorGUILayout.ObjectField(content, (UnityObject)value, t, true));
            }

            if (t == typeof(Type))
            {
                return(Popup <Type>(content, (Type)value, TypePrefs.GetPreferedTypesList(true)));
            }

            if (t == typeof(string))
            {
                return(EditorGUILayout.TextField(content, (string)value));
            }

            if (t == typeof(char))
            {
                var c = (char)value;
                var s = c.ToString();
                s = EditorGUILayout.TextField(content, s);
                return(string.IsNullOrEmpty(s) ? (char)c : (char)s[0]);
            }

            if (t == typeof(bool))
            {
                return(EditorGUILayout.Toggle(content, (bool)value));
            }

            if (t == typeof(int))
            {
                return(EditorGUILayout.IntField(content, (int)value));
            }

            if (t == typeof(float))
            {
                return(EditorGUILayout.FloatField(content, (float)value));
            }

            if (t == typeof(byte))
            {
                return(Convert.ToByte(Mathf.Clamp(EditorGUILayout.IntField(content, (byte)value), 0, 255)));
            }

            if (t == typeof(long))
            {
                return(EditorGUILayout.LongField(content, (long)value));
            }

            if (t == typeof(double))
            {
                return(EditorGUILayout.DoubleField(content, (double)value));
            }

            if (t == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(content, (Vector2)value));
            }

            if (t == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(content, (Vector3)value));
            }

            if (t == typeof(Vector4))
            {
                return(EditorGUILayout.Vector4Field(content, (Vector4)value));
            }

            if (t == typeof(Quaternion))
            {
                var quat = (Quaternion)value;
                var vec4 = new Vector4(quat.x, quat.y, quat.z, quat.w);
                vec4 = EditorGUILayout.Vector4Field(content, vec4);
                return(new Quaternion(vec4.x, vec4.y, vec4.z, vec4.w));
            }

            if (t == typeof(Color))
            {
                return(EditorGUILayout.ColorField(content, (Color)value));
            }

            if (t == typeof(Rect))
            {
                return(EditorGUILayout.RectField(content, (Rect)value));
            }

            if (t == typeof(AnimationCurve))
            {
                return(EditorGUILayout.CurveField(content, (AnimationCurve)value));
            }

            if (t == typeof(Bounds))
            {
                return(EditorGUILayout.BoundsField(content, (Bounds)value));
            }

            if (t == typeof(LayerMask))
            {
                return(LayerMaskField(content, (LayerMask)value));
            }

            if (t.IsSubclassOf(typeof(System.Enum)))
            {
                if (t.IsDefined(typeof(FlagsAttribute), true))
                {
#if UNITY_2017_3_OR_NEWER
                    return(EditorGUILayout.EnumFlagsField(content, (System.Enum)value));
#else
                    return(EditorGUILayout.EnumMaskPopup(content, (System.Enum)value));
#endif
                }
                return(EditorGUILayout.EnumPopup(content, (System.Enum)value));
            }

            if (typeof(IList).IsAssignableFrom(t))
            {
                return(ListEditor(content, (IList)value, t, field, context, attributes));
            }

            if (typeof(IDictionary).IsAssignableFrom(t))
            {
                return(DictionaryEditor(content, (IDictionary)value, t, field, context, attributes));
            }

            //show nested class members recursively
            if (value != null && (t.IsClass || t.IsValueType))
            {
                if (EditorGUI.indentLevel <= 8)
                {
                    GUILayout.BeginVertical();
                    EditorGUILayout.LabelField(content, new GUIContent(string.Format("({0})", t.FriendlyName())));
                    EditorGUI.indentLevel++;
                    ReflectedObjectInspector(value);
                    EditorGUI.indentLevel--;
                    GUILayout.EndVertical();
                }
            }
            else
            {
                EditorGUILayout.LabelField(content, new GUIContent(string.Format("NonInspectable ({0})", t.FriendlyName())));
            }

            return(value);
        }
    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
    {
        FindProperties(props);

        materialEditor.TextureProperty(this.mainTexProperty, "MainTex");

        EditorGUI.BeginChangeCheck();
        SetupBlendMode();

        this.preMulAlphaProperty.floatValue = EditorGUILayout.Toggle("PreMulAlpha", this.preMulAlphaProperty.floatValue != 0) ? 1 : 0;
        if (this.preMulAlphaProperty.floatValue != 1 && blendPreset == BlendPreset.PreMulBlend)
        {
            EditorGUILayout.HelpBox("PreMulBlend模式下建议开启PreMulAlpha,否则不会淡出,并且不支持雾", MessageType.Warning);
        }

        this.revVertColorProperty.floatValue = EditorGUILayout.Toggle("RevVertColor", this.revVertColorProperty.floatValue != 0) ? 1 : 0;
        if (this.revVertColorProperty.floatValue != 1 && blendOp == BlendOp.ReverseSubtract)
        {
            EditorGUILayout.HelpBox("ReverseSubtract模式下建议开启RevVertColor", MessageType.Warning);
        }

        this.revTexColorProperty.floatValue     = EditorGUILayout.Toggle("RevTexColor", this.revTexColorProperty.floatValue != 0) ? 1 : 0;
        this.alphaFromLengthProperty.floatValue = EditorGUILayout.Toggle("AlphaFromLength", this.alphaFromLengthProperty.floatValue != 0) ? 1 : 0;
        if (this.alphaFromLengthProperty.floatValue == 1)
        {
            materialEditor.RangeProperty(alphaIntensityProperty, "AlphaIntensity");
        }


        materialEditor.RangeProperty(this.intensityProperty, "Intensity");
        materialEditor.ColorProperty(this.colorPorperty, "Color");

//		showOther = EditorGUILayout.Foldout(showOther, "Others");
//		if (showOther) {
        EditorGUI.indentLevel = EditorGUI.indentLevel + 1;
        uvMove = new Vector2(this.uvMovePorperty.vectorValue.x, this.uvMovePorperty.vectorValue.y);
        uvMove = EditorGUILayout.Vector2Field("UVMove", uvMove);

        zTest = this.zTestProperty.floatValue == 0f ? false : true;
        zTest = EditorGUILayout.Toggle("ZTest", zTest);

        cullMode = (CullMode)this.cullPorperty.floatValue;
        cullMode = (CullMode)EditorGUILayout.EnumPopup("Cull", cullMode);

        fogEnable = this.fogEnablePorperty.floatValue == 1 ? true : false;
        fogEnable = EditorGUILayout.Toggle("Fog", fogEnable);
        if (fogEnable)
        {
            fogColorEnable = this.fogColorEnablePorperty.floatValue == 1 ? true : false;
            fogColorEnable = EditorGUILayout.Toggle("FogColor", fogColorEnable);
            if (fogColorEnable)
            {
                materialEditor.ColorProperty(this.fogColorPorperty, "FogColor");
            }
        }


        colorWriteMask = (ColorWriteMask)EditorGUILayout.EnumMaskPopup(new GUIContent("ColorMask"), colorWriteMask);
        materialEditor.RangeProperty(this.InvFadePorperty, "Soft Particles Factor");

        stencilComp = (CompareFunction)this.stencilCompPorperty.floatValue;
        stencilComp = (CompareFunction)EditorGUILayout.EnumPopup("_StencilComp", stencilComp);
        if (stencilComp != CompareFunction.Disabled)                  //disabled will turn off stencil
        {
            materialEditor.FloatProperty(this.stencilRefPorperty, "_StencilRef");
            stencilOp = (StencilOp)EditorGUILayout.EnumPopup("_StencilOp", stencilOp);
            materialEditor.FloatProperty(stencilWriteMaskPorperty, "Stencil Write");
            materialEditor.FloatProperty(stencilReadMaskPorperty, "Stencil Read");
        }
//		}


        if (EditorGUI.EndChangeCheck())
        {
            materialEditor.RegisterPropertyChangeUndo("Change Particle Materail");
            ApplyChange(materialEditor);
        }
    }
        protected override void RenderContent(UnityEngine.Object undoRecordObject)
        {
            bool newBool; int newInt;
            MultiSelectOverlapMode newMultiSelectOverlapMode;

            // Can click select
            var content = new GUIContent();

            content.text    = "Can click select";
            content.tooltip = "Allows you to specify if objects can be selected via mouse clicks.";
            newBool         = EditorGUILayout.ToggleLeft(content, CanClickSelect);
            if (newBool != CanClickSelect)
            {
                EditorUndoEx.Record(undoRecordObject);
                CanClickSelect = newBool;
            }

            // Can cyclical click select
            content.text    = "Enable cyclical click select";
            content.tooltip = "If this is checked, each successive click will select an object which lies behind the previously selected one. Useful especially when dealing with overlapping sprites.";
            newBool         = EditorGUILayout.ToggleLeft(content, EnableCyclicalClickSelect);
            if (newBool != EnableCyclicalClickSelect)
            {
                EditorUndoEx.Record(undoRecordObject);
                EnableCyclicalClickSelect = newBool;
            }

            // Can multi select
            content.text    = "Can multi-select";
            content.tooltip = "Allows you to specify if objects can be selected using the multi-select shape.";
            newBool         = EditorGUILayout.ToggleLeft(content, CanMultiSelect);
            if (newBool != CanMultiSelect)
            {
                EditorUndoEx.Record(undoRecordObject);
                CanMultiSelect = newBool;
            }

            content.text              = "Multi-select overlap mode";
            content.tooltip           = "Allows you to specify the way in which objects are selected via the multi-select shape.";
            newMultiSelectOverlapMode = (MultiSelectOverlapMode)EditorGUILayout.EnumPopup(content, MultiSelectOverlapMode);
            if (newMultiSelectOverlapMode != MultiSelectOverlapMode)
            {
                EditorUndoEx.Record(undoRecordObject);
                MultiSelectOverlapMode = newMultiSelectOverlapMode;
            }

            // Selectable object types
            content.text    = "Selectable object types";
            content.tooltip = "Allows you to specify which object types can be selected.";
            newInt          = (int)((GameObjectType)EditorGUILayout.EnumMaskPopup(content, (GameObjectType)_selectableObjectTypes));
            if (newInt != (int)_selectableObjectTypes)
            {
                EditorUndoEx.Record(undoRecordObject);
                _selectableObjectTypes = (GameObjectType)newInt;
            }

            // Selectable layers
            content.text    = "Selectable layers";
            content.tooltip = "Allows you to specify which layers can be selected.";
            newInt          = EditorGUILayoutEx.LayerMaskField(content, _selectableLayers);
            if (newInt != _selectableLayers)
            {
                EditorUndoEx.Record(undoRecordObject);
                _selectableLayers = newInt;
            }

            // Duplicatable layers
            content.text    = "Duplicatable layers";
            content.tooltip = "Allows you to specify which layers can be duplicated.";
            newInt          = EditorGUILayoutEx.LayerMaskField(content, _duplicatableLayers);
            if (newInt != _duplicatableLayers)
            {
                EditorUndoEx.Record(undoRecordObject);
                _duplicatableLayers = newInt;
            }

            // Deletable layers
            content.text    = "Deletable layers";
            content.tooltip = "Allows you to specify which layers can be deleted.";
            newInt          = EditorGUILayoutEx.LayerMaskField(content, _deletableLayers);
            if (newInt != _deletableLayers)
            {
                EditorUndoEx.Record(undoRecordObject);
                _deletableLayers = newInt;
            }

            // Multi-select shape
            content.text    = "Min multi-select size";
            content.tooltip = "The minimum size (width and height) the multi-select shape must have to be able to overlap objects. The value is expressed in pixels.";
            newInt          = EditorGUILayout.IntField(content, MinMultiSelectSize);
            if (newInt != MinMultiSelectSize)
            {
                EditorUndoEx.Record(undoRecordObject);
                MinMultiSelectSize = newInt;
            }
        }
예제 #22
0
    public void BakingGUI(MicroSplatTerrain t)
    {
        if (needsBake && Event.current.type == EventType.Repaint)
        {
            needsBake = false;
            Bake(t);
        }
#if __MICROSPLAT_PROCTEX__
        if (bakeSplats && Event.current.type == EventType.Repaint)
        {
            bakeSplats = false;

            int alphaLayerCount = t.terrain.terrainData.alphamapLayers;
            int splatRes        = t.terrain.terrainData.alphamapResolution;
            int splatCount      = t.terrain.terrainData.terrainLayers.Length;
            float[,,] splats = new float[splatRes, splatRes, splatCount];

            // World/normals are used in texturing, so we have to make them match.
            Texture2D worldPos, worldNormal;
            GenerateWorldData(t.terrain, out worldNormal, out worldPos, splatRes);


            for (int i = 0; i < alphaLayerCount; i = i + 4)
            {
                Texture2D tex   = Texture2D.blackTexture;
                Texture2D alpha = Texture2D.blackTexture;

                if (i == 0)
                {
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput0, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput0A, splatRes, worldPos, worldNormal);
                }
                if (i == 4)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput1, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput1A, splatRes, worldPos, worldNormal);
                }
                else if (i == 8)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput2, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput2A, splatRes, worldPos, worldNormal);
                }
                else if (i == 12)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput3, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput3A, splatRes, worldPos, worldNormal);
                }
                else if (i == 16)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput4, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput4A, splatRes, worldPos, worldNormal);
                }
                else if (i == 20)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput5, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput5A, splatRes, worldPos, worldNormal);
                }
                else if (i == 24)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput6, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput6A, splatRes, worldPos, worldNormal);
                }
                else if (i == 28)
                {
                    DestroyTex(tex);
                    DestroyTex(alpha);
                    tex   = Bake(t, BakingPasses.ProceduralSplatOutput7, splatRes, worldPos, worldNormal);
                    alpha = Bake(t, BakingPasses.ProceduralSplatOutput7A, splatRes, worldPos, worldNormal);
                }

                for (int x = 0; x < splatRes; ++x)
                {
                    for (int y = 0; y < splatRes; ++y)
                    {
                        Color c = tex.GetPixel(x, y);
                        Color a = alpha.GetPixel(x, y);
                        if (i < splatCount)
                        {
                            splats[y, x, i] = c.r;
                        }
                        if (i + 1 < splatCount)
                        {
                            splats[y, x, i + 1] = c.g;
                        }
                        if (i + 2 < splatCount)
                        {
                            splats[y, x, i + 2] = c.b;
                        }
                        if (i + 3 < splatCount)
                        {
                            splats[y, x, i + 3] = a.g;
                        }
                    }
                }
            }
            DestroyImmediate(worldPos);
            DestroyImmediate(worldNormal);
            t.terrain.terrainData.SetAlphamaps(0, 0, splats);
            EditorUtility.SetDirty(t.terrain.terrainData);
        }
#endif

        if (MicroSplatUtilities.DrawRollup("Render Baking", false))
        {
            res = (BakingResolutions)EditorGUILayout.EnumPopup(new GUIContent("Resolution"), res);

         #if UNITY_2017_3_OR_NEWER
            passes = (BakingPasses)EditorGUILayout.EnumFlagsField(new GUIContent("Features"), passes);
         #else
            passes = (BakingPasses)EditorGUILayout.EnumMaskPopup(new GUIContent("Features"), passes);
         #endif

            if (GUILayout.Button("Export Selected"))
            {
                needsBake = true;
            }
        }
#if __MICROSPLAT_PROCTEX__
        if (t.templateMaterial != null && t.keywordSO != null && t.keywordSO.IsKeywordEnabled("_PROCEDURALTEXTURE"))
        {
            if (MicroSplatUtilities.DrawRollup("Procedural Baking", false))
            {
                EditorGUILayout.Space();
                if (GUILayout.Button("Bake Procedural to Terrain"))
                {
                    bakeSplats = true;
                }
                EditorGUILayout.Space();
            }
        }
#endif
        MicroSplatCompressor.DrawGUI(t, compressOptions);
    }
        private bool EditCocoStoreItem(int pIndex)
        {
            if (GlobalSettingData.Instance == null)
            {
                return(false);
            }

            var pIsRemoveData = false;

            var pPlatformItem = GlobalSettingData.Instance.allPlatformItems [pIndex];

            var box = EditorGUILayout.BeginVertical(GUI.skin.box);

            var pRect = new Rect(box.xMax - 50, box.yMin + 2, 50, 15);

            if (GUI.Button(pRect, "X"))
            {
                pIsRemoveData = true;
            }

            pRect = new Rect(box.xMax - 180, box.yMin + 2, 100, 15);
            if (GUI.Button(pRect, "选择平台"))
            {
                SwitchPlatformByItem(pPlatformItem);
            }

            pPlatformItem.foldout = EditorGUILayout.Foldout(pPlatformItem.foldout, pPlatformItem.curPlatform.ToString());
            GUILayout.Space(8);

            if (pPlatformItem.foldout)
            {
                if (pPlatformItem.isSelected)
                {
                    EditorGUILayout.Toggle("已选择", pPlatformItem.isSelected);
                }

                pPlatformItem.curPlatform   = (MultiPlatformType)EditorGUILayout.EnumPopup("curPlatform (平台类型): ", pPlatformItem.curPlatform);
                pPlatformItem.bundleId      = EditorGUILayout.TextField("bundleId: ", pPlatformItem.bundleId);
                pPlatformItem.bundleVersion = EditorGUILayout.TextField("bundleVersion(版本号): ", pPlatformItem.bundleVersion);

                pPlatformItem.iconFolder = EditorGUILayout.TextField("IconFolder(图标文件夹): ", pPlatformItem.iconFolder);

                pPlatformItem.allowOrientations =
                    (MultiPlatformItem.Orientation)EditorGUILayout.EnumMaskPopup("orientations(允许屏幕方向)", pPlatformItem.allowOrientations);

                switch (pPlatformItem.curPlatform)
                {
                case MultiPlatformType.iOS:

                    break;

                case MultiPlatformType.GooglePlay:
                case MultiPlatformType.Amazon:
                    pPlatformItem.bundleVersionCode = EditorGUILayout.IntField("bundleVersionCode: ", pPlatformItem.bundleVersionCode);

                    pPlatformItem.keystoreName = EditorGUILayout.TextField("keystoreName: ", pPlatformItem.keystoreName);
                    pPlatformItem.keystorePass = EditorGUILayout.TextField("keystorePass: "******"keyaliasName: ", pPlatformItem.keyaliasName);
                    pPlatformItem.keyaliasPass = EditorGUILayout.TextField("keyaliasPass: "******"scriptingDefs(宏定义): ", pPlatformItem.scriptingDefs);

                pPlatformItem.splitBinary = EditorGUILayout.Toggle("splitBinary(分包): ", pPlatformItem.splitBinary);
            }

            GlobalSettingData.Instance.allPlatformItems [pIndex] = pPlatformItem;

            EditorGUILayout.EndVertical();

            return(pIsRemoveData);
        }
   public void BakingGUI(MicroSplatTerrain t)
   {
      if (needsBake && Event.current.type == EventType.Repaint)
      {
         needsBake = false;
         Bake(t);
      }
#if __MICROSPLAT_PROCTEX__


      if (bakeSplats && Event.current.type == EventType.Repaint)
      {
         bakeSplats = false;
         
         int alphaLayerCount = t.terrain.terrainData.alphamapLayers;
         int splatRes = t.terrain.terrainData.alphamapResolution;
      #if UNITY_2019_3_OR_NEWER
         int splatCount = t.terrain.terrainData.terrainLayers.Length;
      #else
         int splatCount = t.terrain.terrainData.splatPrototypes.Length;
      #endif
         float[,,] splats = new float[splatRes, splatRes, splatCount];

         // World/normals are used in texturing, so we have to make them match.
         Texture2D worldPos = new Texture2D(splatRes, splatRes, TextureFormat.RGBAFloat, true, true);
         Texture2D worldNormal = new Texture2D(splatRes, splatRes, TextureFormat.RGBAFloat, true, true);
         t.terrain.transform.rotation = Quaternion.identity;
         for (int x = 0; x < splatRes; ++x)
         {
            float u = (float)x / (float)splatRes;
            for (int y = 0; y < splatRes; ++y)
            {
               float v = (float)y / (float)splatRes;
               float h = t.terrain.terrainData.GetInterpolatedHeight(u, v);
               Vector3 n = t.terrain.terrainData.GetInterpolatedNormal(u, v);

               Vector3 wp = t.terrain.transform.localToWorldMatrix.MultiplyPoint(new Vector3(u * t.terrain.terrainData.size.x, h, v * t.terrain.terrainData.size.z));
               worldPos.SetPixel(x, y, new Color(wp.x, wp.y, wp.z));
               worldNormal.SetPixel(x, y, new Color(n.x, n.y, n.z));
            }
         }
         worldPos.Apply();
         worldNormal.Apply();

         for (int i = 0; i < alphaLayerCount; i=i+4)
         {
            Texture2D tex = Texture2D.blackTexture;
            Texture2D alpha = Texture2D.blackTexture;

            if (i == 0)
            {
               tex = Bake(t, BakingPasses.ProceduralSplatOutput0, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput0A, splatRes, worldPos, worldNormal);
            }
            if (i == 4)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput1, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput1A, splatRes, worldPos, worldNormal);
            }
            else if (i == 8)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput2, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput2A, splatRes, worldPos, worldNormal);
            }
            else if (i == 12)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput3, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput3A, splatRes, worldPos, worldNormal);
            }
            else if (i == 16)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput4, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput4A, splatRes, worldPos, worldNormal);
            }
            else if (i == 20)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput5, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput5A, splatRes, worldPos, worldNormal);
            }
            else if (i == 24)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput6, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput6A, splatRes, worldPos, worldNormal);
            }
            else if (i == 28)
            {
               DestroyImmediate(tex);
               DestroyImmediate(alpha);
               tex = Bake(t, BakingPasses.ProceduralSplatOutput7, splatRes, worldPos, worldNormal);
               alpha = Bake(t, BakingPasses.ProceduralSplatOutput7A, splatRes, worldPos, worldNormal);
            }

            for (int x = 0; x < splatRes; ++x)
            {
               for (int y = 0; y < splatRes; ++y)
               {
                  Color c = tex.GetPixel(x, y);
                  Color a = alpha.GetPixel(x, y);
                  if (i < splatCount)
                  {
                     splats[y, x, i] = c.r;
                  }
                  if (i + 1 < splatCount)
                  {
                     splats[y, x, i + 1] = c.g;
                  }
                  if (i + 2 < splatCount)
                  {
                     splats[y, x, i + 2] = c.b;
                  }
                  if (i + 3 < splatCount)
                  {
                     splats[y, x, i + 3] = a.g;
                  }
               }
            }
         }
         DestroyImmediate(worldPos);
         DestroyImmediate(worldNormal);
         t.terrain.terrainData.SetAlphamaps(0, 0, splats);
         EditorUtility.SetDirty(t.terrain.terrainData);

      }
#endif

      if (MicroSplatUtilities.DrawRollup("Render Baking", false))
      {
         res = (BakingResolutions)EditorGUILayout.EnumPopup(new GUIContent("Resolution"), res);

         #if UNITY_2017_3_OR_NEWER
            passes = (BakingPasses)EditorGUILayout.EnumFlagsField(new GUIContent("Features"), passes);
         #else
            passes = (BakingPasses)EditorGUILayout.EnumMaskPopup(new GUIContent("Features"), passes);
         #endif

         if (GUILayout.Button("Export Selected"))
         {
            needsBake = true;
         }

#if __MICROSPLAT_PROCTEX__
         if (t.templateMaterial != null && t.keywordSO != null && t.keywordSO.IsKeywordEnabled("_PROCEDURALTEXTURE"))
         {
            EditorGUILayout.Space();
            EditorGUILayout.Space();
            if (GUILayout.Button("Bake Procedural to Terrain"))
            {
               bakeSplats = true;
            }
            EditorGUILayout.Space();
            EditorGUILayout.Space();
         }
#endif

      }
   }
예제 #25
0
        public override void OnInspectorGUI()
        {
            //return;

            //base.OnInspectorGUI();
            apPortrait targetPortrait = target as apPortrait;

            if (targetPortrait != _targetPortrait)
            {
                _targetPortrait = targetPortrait;
                Init();
            }
            if (_targetPortrait == null)
            {
                //Profiler.EndSample();
                return;
            }

            //Profiler.BeginSample("anyPortrait Inspector GUI");


            //return;
            if (apEditor.IsOpen())
            {
                //에디터가 작동중에는 안보이도록 하자
                EditorGUILayout.LabelField("Editor is opened");

                //Profiler.EndSample();

                return;
            }

            try
            {
                bool          request_OpenEditor    = false;
                bool          request_QuickBake     = false;
                bool          request_RefreshMeshes = false;
                bool          prevImportant         = _targetPortrait._isImportant;
                MonoBehaviour prevAnimEventListener = _targetPortrait._optAnimEventListener;
                int           prevSortingLayerID    = _targetPortrait._sortingLayerID;
                int           prevSortingOrder      = _targetPortrait._sortingOrder;

                if (!EditorApplication.isPlaying)
                {
                    if (!_targetPortrait._isOptimizedPortrait)
                    {
                        GUILayout.Space(10);
                        if (GUILayout.Button("Open Editor and Select", GUILayout.Height(30)))
                        {
                            request_OpenEditor = true;
                        }
                        if (GUILayout.Button("Quick Bake", GUILayout.Height(25)))
                        {
                            request_QuickBake = true;
                        }
                    }
                    else
                    {
                        GUILayout.Space(10);
                        if (GUILayout.Button("Open Editor (Not Selectable)", GUILayout.Height(30)))
                        {
                            //열기만 하고 선택은 못함
                            request_OpenEditor = true;
                        }
                    }
                    //추가 12.18 : Mesh를 리프레시 하자
                    if (GUILayout.Button("Refresh Meshes", GUILayout.Height(25)))
                    {
                        request_RefreshMeshes = true;
                    }
                }

                GUILayout.Space(10);

                _targetPortrait._isImportant          = EditorGUILayout.Toggle("Is Important", _targetPortrait._isImportant);
                _targetPortrait._optAnimEventListener = (MonoBehaviour)EditorGUILayout.ObjectField("Event Listener", _targetPortrait._optAnimEventListener, typeof(MonoBehaviour), true);


                GUILayout.Space(5);
                //추가3.22
                //Sorting Layer
                string[] sortingLayerName = new string[SortingLayer.layers.Length];
                int      layerIndex       = -1;
                for (int i = 0; i < SortingLayer.layers.Length; i++)
                {
                    sortingLayerName[i] = SortingLayer.layers[i].name;
                    if (SortingLayer.layers[i].id == _targetPortrait._sortingLayerID)
                    {
                        layerIndex = i;
                    }
                }
                int nextLayerIndex = EditorGUILayout.Popup("Sorting Layer", layerIndex, sortingLayerName);
                int nextLayerOrder = EditorGUILayout.IntField("Sorting Order", _targetPortrait._sortingOrder);

                if (nextLayerIndex != layerIndex)
                {
                    //Sorting Layer를 바꾸자
                    if (nextLayerIndex >= 0 && nextLayerIndex < SortingLayer.layers.Length)
                    {
                        string nextLayerName = SortingLayer.layers[nextLayerIndex].name;
                        _targetPortrait.SetSortingLayer(nextLayerName);
                    }
                }
                if (nextLayerOrder != _targetPortrait._sortingOrder)
                {
                    _targetPortrait.SetSortingOrder(nextLayerOrder);
                }


                if (prevImportant != _targetPortrait._isImportant ||
                    prevAnimEventListener != _targetPortrait._optAnimEventListener ||
                    prevSortingLayerID != _targetPortrait._sortingLayerID ||
                    prevSortingOrder != _targetPortrait._sortingOrder)
                {
                    apEditorUtil.SetEditorDirty();
                }


                GUILayout.Space(5);

                //빌보드
                apPortrait.BILLBOARD_TYPE nextBillboard = (apPortrait.BILLBOARD_TYPE)EditorGUILayout.EnumPopup("Billboard Type", _targetPortrait._billboardType);
                if (nextBillboard != _targetPortrait._billboardType)
                {
                    _targetPortrait._billboardType = nextBillboard;
                    apEditorUtil.SetEditorDirty();
                }

                GUILayout.Space(5);

                _isFold_RootPortraits = EditorGUILayout.Foldout(_isFold_RootPortraits, "Root Portraits");
                if (_isFold_RootPortraits)
                {
                    string strRootPortrait = "";
                    if (_targetPortrait._optRootUnitList.Count == 0)
                    {
                        strRootPortrait = "No Baked Portrait";
                    }
                    else if (_targetPortrait._optRootUnitList.Count == 1)
                    {
                        strRootPortrait = "1 Baked Portrait";
                    }
                    else
                    {
                        strRootPortrait = _targetPortrait._optRootUnitList.Count + " Baked Portraits";
                    }
                    EditorGUILayout.LabelField(strRootPortrait);
                    GUILayout.Space(5);
                    for (int i = 0; i < _targetPortrait._optRootUnitList.Count; i++)
                    {
                        apOptRootUnit rootUnit = _targetPortrait._optRootUnitList[i];
                        EditorGUILayout.ObjectField("[" + i + "]", rootUnit, typeof(apOptRootUnit), true);
                    }

                    GUILayout.Space(20);
                }



                _isFold_AnimationClips = EditorGUILayout.Foldout(_isFold_AnimationClips, "Animation Settings");
                if (_isFold_AnimationClips)
                {
                    EditorGUILayout.LabelField("Animation Clips");
                    string strAnimClips = "";
                    if (_targetPortrait._animClips.Count == 0)
                    {
                        strAnimClips = "No Animation Clip";
                    }
                    else if (_targetPortrait._animClips.Count == 1)
                    {
                        strAnimClips = "1 Animation Clip";
                    }
                    else
                    {
                        strAnimClips = _targetPortrait._animClips.Count + " Animation Clips";
                    }
                    EditorGUILayout.LabelField(strAnimClips);
                    GUILayout.Space(5);


                    for (int i = 0; i < _targetPortrait._animClips.Count; i++)
                    {
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(5);
                        apAnimClip animClip = _targetPortrait._animClips[i];
                        if (animClip._uniqueID == _targetPortrait._autoPlayAnimClipID)
                        {
                            EditorGUILayout.LabelField("[" + i + "] (Auto)", GUILayout.Width(80));
                        }
                        else
                        {
                            EditorGUILayout.LabelField("[" + i + "]", GUILayout.Width(80));
                        }
                        EditorGUILayout.TextField(animClip._name);
                        try
                        {
                            AnimationClip nextAnimationClip = EditorGUILayout.ObjectField(animClip._animationClipForMecanim, typeof(AnimationClip), false) as AnimationClip;
                            if (nextAnimationClip != animClip._animationClipForMecanim)
                            {
                                UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                                Undo.IncrementCurrentGroup();
                                Undo.RegisterCompleteObjectUndo(_targetPortrait, "Animation Changed");

                                animClip._animationClipForMecanim = nextAnimationClip;
                            }
                        }
                        catch (Exception)
                        { }

                        EditorGUILayout.EndHorizontal();
                    }
                    GUILayout.Space(10);
                    AnimationClip nextEmptyAnimClip = EditorGUILayout.ObjectField("Empty Animation Clip", _targetPortrait._emptyAnimClipForMecanim, typeof(AnimationClip), false) as AnimationClip;
                    if (nextEmptyAnimClip != _targetPortrait._emptyAnimClipForMecanim)
                    {
                        UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                        Undo.IncrementCurrentGroup();
                        Undo.RegisterCompleteObjectUndo(_targetPortrait, "Animation Changed");

                        _targetPortrait._emptyAnimClipForMecanim = nextEmptyAnimClip;
                    }

                    GUILayout.Space(10);
                    EditorGUILayout.LabelField("Mecanim Settings");
                    bool isNextUsingMecanim = EditorGUILayout.Toggle("Use Mecanim", _targetPortrait._isUsingMecanim);
                    if (_targetPortrait._isUsingMecanim != isNextUsingMecanim)
                    {
                        UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                        Undo.IncrementCurrentGroup();
                        Undo.RegisterCompleteObjectUndo(_targetPortrait, "Mecanim Setting Changed");

                        _targetPortrait._isUsingMecanim = isNextUsingMecanim;
                    }


                    if (_targetPortrait._isUsingMecanim)
                    {
                        GUILayout.Space(10);
                        try
                        {
                            Animator nextAnimator = EditorGUILayout.ObjectField("Animator", _targetPortrait._animator, typeof(Animator), true) as Animator;
                            if (nextAnimator != _targetPortrait._animator)
                            {
                                //하위에 있는 Component일 때에만 변동 가능
                                if (nextAnimator == null)
                                {
                                    _targetPortrait._animator = null;
                                }
                                else
                                {
                                    if (nextAnimator == _targetPortrait.GetComponent <Animator>())
                                    {
                                        _targetPortrait._animator = nextAnimator;
                                    }
                                    else
                                    {
                                        EditorUtility.DisplayDialog("Invalid Animator", "Invalid Animator. Only the Animator, which is its own component, is valid.", "Okay");
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        if (_targetPortrait._animator == null)
                        {
                            //1. Animator가 없다면
                            // > 생성하기
                            // > 생성되어 있다면 다시 링크
                            GUIStyle guiStyle_WarningText = new GUIStyle(GUI.skin.label);
                            guiStyle_WarningText.normal.textColor = Color.red;
                            EditorGUILayout.LabelField("Warning : No Animator!", guiStyle_WarningText);
                            GUILayout.Space(5);

                            if (GUILayout.Button("Add / Check Animator", GUILayout.Height(25)))
                            {
                                UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                                Undo.IncrementCurrentGroup();
                                Undo.RegisterCompleteObjectUndo(_targetPortrait, "Mecanim Setting Changed");

                                Animator animator = _targetPortrait.gameObject.GetComponent <Animator>();
                                if (animator == null)
                                {
                                    animator = _targetPortrait.gameObject.AddComponent <Animator>();
                                }
                                _targetPortrait._animator = animator;
                            }
                        }
                        else
                        {
                            //2. Animator가 있다면
                            if (GUILayout.Button("Refresh Layers", GUILayout.Height(25)))
                            {
                                UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                                Undo.IncrementCurrentGroup();
                                Undo.RegisterCompleteObjectUndo(_targetPortrait, "Mecanim Setting Changed");

                                //Animator의 Controller가 있는지 체크해야한다.

                                if (_targetPortrait._animator.runtimeAnimatorController == null)
                                {
                                    //AnimatorController가 없다면 Layer는 초기화
                                    _targetPortrait._animatorLayerBakedData.Clear();
                                }
                                else
                                {
                                    //AnimatorController가 있다면 레이어에 맞게 설정
                                    _targetPortrait._animatorLayerBakedData.Clear();
                                    UnityEditor.Animations.AnimatorController animatorController = _targetPortrait._animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController;

                                    if (animatorController != null && animatorController.layers.Length > 0)
                                    {
                                        for (int iLayer = 0; iLayer < animatorController.layers.Length; iLayer++)
                                        {
                                            apAnimMecanimData_Layer newLayerData = new apAnimMecanimData_Layer();
                                            newLayerData._layerIndex = iLayer;
                                            newLayerData._layerName  = animatorController.layers[iLayer].name;
                                            newLayerData._blendType  = apAnimMecanimData_Layer.MecanimLayerBlendType.Unknown;
                                            switch (animatorController.layers[iLayer].blendingMode)
                                            {
                                            case UnityEditor.Animations.AnimatorLayerBlendingMode.Override:
                                                newLayerData._blendType = apAnimMecanimData_Layer.MecanimLayerBlendType.Override;
                                                break;

                                            case UnityEditor.Animations.AnimatorLayerBlendingMode.Additive:
                                                newLayerData._blendType = apAnimMecanimData_Layer.MecanimLayerBlendType.Additive;
                                                break;
                                            }

                                            _targetPortrait._animatorLayerBakedData.Add(newLayerData);
                                        }
                                    }
                                }
                            }
                            GUILayout.Space(5);
                            EditorGUILayout.LabelField("Animator Controller Layers");
                            for (int i = 0; i < _targetPortrait._animatorLayerBakedData.Count; i++)
                            {
                                apAnimMecanimData_Layer layer = _targetPortrait._animatorLayerBakedData[i];
                                EditorGUILayout.BeginHorizontal();
                                GUILayout.Space(5);
                                EditorGUILayout.LabelField("[" + layer._layerIndex + "]", GUILayout.Width(50));
                                EditorGUILayout.TextField(layer._layerName);
                                apAnimMecanimData_Layer.MecanimLayerBlendType nextBlendType = (apAnimMecanimData_Layer.MecanimLayerBlendType)EditorGUILayout.EnumPopup(layer._blendType);
                                EditorGUILayout.EndHorizontal();

                                if (nextBlendType != layer._blendType)
                                {
                                    UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
                                    Undo.IncrementCurrentGroup();
                                    Undo.RegisterCompleteObjectUndo(_targetPortrait, "Mecanim Setting Changed");

                                    _targetPortrait._animatorLayerBakedData[i]._blendType = nextBlendType;
                                }
                            }
                        }
                    }


                    GUILayout.Space(20);
                }


                bool isChanged = false;

                _isFold_ConrolParameters = EditorGUILayout.Foldout(_isFold_ConrolParameters, "Control Parameters");
                if (_isFold_ConrolParameters)
                {
#if UNITY_2017_3_OR_NEWER
                    _curControlCategory = (apControlParam.CATEGORY)EditorGUILayout.EnumFlagsField(new GUIContent("Category"), _curControlCategory);
#else
                    _curControlCategory = (apControlParam.CATEGORY)EditorGUILayout.EnumMaskPopup(new GUIContent("Category"), _curControlCategory);
#endif

                    EditorGUILayout.Space();
                    //1. 컨르롤러를 제어할 수 있도록 하자

                    if (_controlParams != null)
                    {
                        for (int i = 0; i < _controlParams.Count; i++)
                        {
                            if ((int)(_controlParams[i]._category & _curControlCategory) != 0)
                            {
                                if (GUI_ControlParam(_controlParams[i]))
                                {
                                    isChanged = true;
                                }
                            }
                        }
                    }

                    GUILayout.Space(20);
                }


                GUILayout.Space(10);

                //2. 토글 버튼을 두어서 기본 Inspector 출력 여부를 결정하자.
                string strBaseButton = "Show All Properties";
                if (_showBaseInspector)
                {
                    strBaseButton = "Hide Properties";
                }

                if (GUILayout.Button(strBaseButton, GUILayout.Height(20)))
                {
                    _showBaseInspector = !_showBaseInspector;
                }

                if (_showBaseInspector)
                {
                    base.OnInspectorGUI();
                }


                if (!Application.isPlaying && isChanged)
                {
                    //플레이 중이라면 자동으로 업데이트 될 것이다.
                    _targetPortrait.UpdateForce();
                }

                if (_targetPortrait != null)
                {
                    if (request_OpenEditor)
                    {
                        if (_targetPortrait._isOptimizedPortrait)
                        {
                            RequestDelayedOpenEditor(_targetPortrait, REQUEST_TYPE.Open);
                        }
                        else
                        {
                            RequestDelayedOpenEditor(_targetPortrait, REQUEST_TYPE.OpenAndSet);
                        }
                        //apEditor anyPortraitEditor = apEditor.ShowWindow();
                        //if (anyPortraitEditor != null && !_targetPortrait._isOptimizedPortrait)
                        //{
                        //	anyPortraitEditor.SetPortraitByInspector(_targetPortrait, false);
                        //}
                    }
                    else if (request_QuickBake)
                    {
                        RequestDelayedOpenEditor(_targetPortrait, REQUEST_TYPE.QuickBake);
                        //apEditor anyPortraitEditor = apEditor.ShowWindow();
                        //if (anyPortraitEditor != null)
                        //{
                        //	anyPortraitEditor.SetPortraitByInspector(_targetPortrait, true);

                        //	Selection.activeObject = _targetPortrait.gameObject;
                        //}
                    }
                    else if (request_RefreshMeshes)
                    {
                        _targetPortrait.OnMeshResetInEditor();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("apInspector_Portrait Exception : " + ex);
            }

            //Profiler.EndSample();
        }
예제 #26
0
        //For generic automatic editors. Passing a MemberInfo will also check for attributes
        public static object GenericField(string name, object value, Type t, MemberInfo member = null, object context = null)
        {
            if (t == null)
            {
                GUILayout.Label("NO TYPE PROVIDED!");
                return(value);
            }

            //Preliminary Hides
            if (typeof(Delegate).IsAssignableFrom(t))
            {
                return(value);
            }
            //

            IEnumerable <Attribute> attributes = new Attribute[0];

            if (member != null)
            {
                //Hide class?
                if (t.GetCustomAttributes(typeof(HideInInspector), true).FirstOrDefault() != null)
                {
                    return(value);
                }

                attributes = member.GetCustomAttributes(true).Cast <Attribute>();

                //Hide field?
                if (attributes.Any(a => a is HideInInspector))
                {
                    return(value);
                }
            }


            //Then check UnityObjects
            if (typeof(UnityObject).IsAssignableFrom(t))
            {
                if (t == typeof(Component) && (Component)value != null)
                {
                    return(ComponentField(name, (Component)value, typeof(Component)));
                }
                return(EditorGUILayout.ObjectField(name, (UnityObject)value, t, typeof(Component).IsAssignableFrom(t) || t == typeof(GameObject)));
            }


            //Check abstract
            if ((value != null && value.GetType().IsAbstract) || (value == null && t.IsAbstract))
            {
                EditorGUILayout.LabelField(name, string.Format("Abstract ({0})", t.Name));
                return(value);
            }

            //Create instance for some types
            if (value == null && !t.IsAbstract && !t.IsInterface && (t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null || t.IsArray))
            {
                if (t.IsArray)
                {
                    value = Array.CreateInstance(t.GetElementType(), 0);
                }
                else
                {
                    value = Activator.CreateInstance(t);
                }
            }



            //Check the rest
            //..............
            if (t == typeof(string))
            {
                return(EditorGUILayout.TextField(name, (string)value));
            }

            if (t == typeof(bool))
            {
                return(EditorGUILayout.Toggle(name, (bool)value));
            }

            if (t == typeof(int))
            {
                return(EditorGUILayout.IntField(name, (int)value));
            }

            if (t == typeof(float))
            {
                return(EditorGUILayout.FloatField(name, (float)value));
            }

            if (t == typeof(byte))
            {
                return(Convert.ToByte(Mathf.Clamp(EditorGUILayout.IntField(name, (byte)value), 0, 255)));
            }

            if (t == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(name, (Vector2)value));
            }

            if (t == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(name, (Vector3)value));
            }

            if (t == typeof(Vector4))
            {
                return(EditorGUILayout.Vector4Field(name, (Vector4)value));
            }

            if (t == typeof(Quaternion))
            {
                var quat = (Quaternion)value;
                var vec4 = new Vector4(quat.x, quat.y, quat.z, quat.w);
                vec4 = EditorGUILayout.Vector4Field(name, vec4);
                return(new Quaternion(vec4.x, vec4.y, vec4.z, vec4.w));
            }

            if (t == typeof(Color))
            {
                return(EditorGUILayout.ColorField(name, (Color)value));
            }

            if (t == typeof(Rect))
            {
                return(EditorGUILayout.RectField(name, (Rect)value));
            }

            if (t == typeof(AnimationCurve))
            {
                return(EditorGUILayout.CurveField(name, (AnimationCurve)value));
            }

            if (t == typeof(Bounds))
            {
                return(EditorGUILayout.BoundsField(name, (Bounds)value));
            }

            if (t == typeof(LayerMask))
            {
                return(LayerMaskField(name, (LayerMask)value));
            }

            if (t.IsSubclassOf(typeof(System.Enum)))
            {
#if UNITY_5
                if (t.GetCustomAttributes(typeof(FlagsAttribute), true).FirstOrDefault() != null)
                {
                    return(EditorGUILayout.EnumMaskPopup(new GUIContent(name), (System.Enum)value));
                }
#endif
                return(EditorGUILayout.EnumPopup(name, (System.Enum)value));
            }

            if (typeof(IList).IsAssignableFrom(t))
            {
                return(ListEditor(name, (IList)value, t, context));
            }

            if (typeof(IDictionary).IsAssignableFrom(t))
            {
                return(DictionaryEditor(name, (IDictionary)value, t, context));
            }

            //show nested class members recursively
            if (value != null && !t.IsEnum && !t.IsInterface)
            {
                GUILayout.BeginVertical();
                EditorGUILayout.LabelField(name, t.Name);
                EditorGUI.indentLevel++;
                ShowAutoEditorGUI(value);
                EditorGUI.indentLevel--;
                GUILayout.EndVertical();
            }
            else
            {
                EditorGUILayout.LabelField(name, string.Format("({0})", t.Name));
            }

            return(value);
        }
        private void DrawMember(SerializedProperty property, ref int index, ParameterData parameter)
        {
            var label = this.labels[index];

            switch (parameter.returnType)
            {
            case ObjectType.Boolean:
            case ObjectType.Int32:
            case ObjectType.Int64:
            case ObjectType.Single:
            case ObjectType.Double:
            case ObjectType.String:
            case ObjectType.LayerMask:
            case ObjectType.Color:
            case ObjectType.AnimationCurve:
                EditorGUILayout.PropertyField(property, label, false);
                break;

            case ObjectType.UInt64:
                var   oldString   = property.stringValue;
                var   ulongString = EditorGUILayout.TextField(label, property.stringValue);
                ulong ulongVal;

                if (!ulong.TryParse(ulongString, out ulongVal))
                {
                    ulongString = oldString;
                }

                if (string.IsNullOrEmpty(ulongString))
                {
                    ulongString = "0";
                }

                property.stringValue = ulongString;
                break;

            case ObjectType.Byte:
                property.intValue = EditorFields.ByteField(label, (byte)property.intValue);
                break;

            case ObjectType.SByte:
                property.intValue = EditorFields.SByteField(label, (sbyte)property.intValue);
                break;

            case ObjectType.Char:
                property.intValue = EditorFields.CharField(label, (char)property.intValue);
                break;

            case ObjectType.Int16:
                property.intValue = EditorFields.ShortField(label, (short)property.intValue);
                break;

            case ObjectType.UInt16:
                property.intValue = EditorFields.UShortField(label, (ushort)property.intValue);
                break;

            case ObjectType.UInt32:
                property.longValue = EditorFields.UIntField(label, (uint)property.longValue);
                break;

            case ObjectType.Enum:
            {
                var  typeOf         = Type.GetType(parameter.assemblyQualifiedName);
                var  flagsAttribute = typeOf.GetCustomAttributes(typeof(FlagsAttribute), false);
                Enum enumValue;

                if (flagsAttribute != null && flagsAttribute.Length >= 1)
                {
                    enumValue = EditorGUILayout.EnumMaskPopup(label, (Enum)Enum.ToObject(typeOf, property.longValue));
                }
                else
                {
                    enumValue = EditorGUILayout.EnumPopup(label, (Enum)Enum.ToObject(typeOf, property.longValue));
                }

                try
                {
                    property.longValue = (int)Enum.ToObject(typeOf, enumValue);
                }
                catch
                {
                    property.longValue = (long)Enum.ToObject(typeOf, enumValue);
                }
            }
            break;

            case ObjectType.Vector2:
                property.vector2Value = EditorGUILayout.Vector2Field(label, property.vector2Value);
                break;

            case ObjectType.Vector3:
                property.vector3Value = EditorGUILayout.Vector3Field(label, property.vector3Value);
                break;

            case ObjectType.Vector4:
                property.vector4Value = EditorGUILayout.Vector4Field(label, property.vector4Value);
                break;

            case ObjectType.Bounds:
                property.boundsValue = EditorGUILayout.BoundsField(label, property.boundsValue);
                break;

            case ObjectType.Rect:
                property.rectValue = EditorGUILayout.RectField(label, property.rectValue);
                break;

            case ObjectType.Quaternion:
                property.quaternionValue = EditorFields.QuaternionField(label, property.quaternionValue);
                break;

            case ObjectType.UnityObject:
            {
                var typeOf = Type.GetType(parameter.assemblyQualifiedName);
                property.objectReferenceValue = EditorGUILayout.ObjectField(label, property.objectReferenceValue, typeOf, true);
            }
            break;

            case ObjectType.Matrix4x4:
            {
                var matrix = property.stringValue.ToObject <Matrix4x4>();
                matrix = EditorFields.Matrix4x4Field(label, matrix);
                property.stringValue = matrix.ToJson();
            }
            break;

            case ObjectType.SerializableType:
            case ObjectType.Array:
            case ObjectType.List:
            {
                var typeOf = Type.GetType(parameter.assemblyQualifiedName);

                if (this.cloneObjects[index] == null)
                {
                    var cloneObjectType = CreateCloneObjectType("CloneObject", FakeObjectFields.Value, typeOf);
                    this.cloneObjects[index]         = CreateInstance(cloneObjectType);
                    this.cloneValueFieldInfos[index] = cloneObjectType.GetField(FakeObjectFields.Value,
                                                                                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                }

                var cloneObject         = this.cloneObjects[index];
                var cloneValueFieldInfo = this.cloneValueFieldInfos[index];

                var data = property.stringValue.ToObject(typeOf);

                if (data == null)
                {
                    if (parameter.returnType == ObjectType.Array)
                    {
                        data = Activator.CreateInstance(typeOf, 0);
                    }
                    else
                    {
                        data = Activator.CreateInstance(typeOf);
                    }
                }

                cloneValueFieldInfo.SetValue(cloneObject, data);

                if (this.serializedCloneObjects[index] == null)
                {
                    this.serializedCloneObjects[index]    = new SerializedObject(cloneObject);
                    this.serializedCloneProperties[index] = this.serializedCloneObjects[index].FindProperty(FakeObjectFields.Value);
                }

                var serializedCloneObject   = this.serializedCloneObjects[index];
                var serializedCloneProperty = this.serializedCloneProperties[index];

                EditorGUI.BeginChangeCheck();

                serializedCloneObject.Update();
                EditorGUILayout.PropertyField(serializedCloneProperty, label, true);

                if (EditorGUI.EndChangeCheck())
                {
                    serializedCloneObject.ApplyModifiedPropertiesWithoutUndo();
                    data = cloneValueFieldInfo.GetValue(cloneObject);

                    property.stringValue = data.ToJson(typeOf);
                }
            }
            break;
            }
        }
예제 #28
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            MapStyle mapStyle = serializedObject.targetObject as MapStyle;

            if (mapStyle == null)
            {
                // ????
                return;
            }

            GUILayout.Label("Editing options", labelBoldStyle);

            var liveUpdateProperty = serializedObject.FindProperty("liveUpdateEnabled");

            EditorGUILayout.PropertyField(liveUpdateProperty, new GUIContent {
                text = "Update RegionMap while editing"
            });

            GUILayout.Space(EditorGUIUtility.singleLineHeight);

            GUILayout.Label("Layers", labelBoldStyle);

            layerTreeView.Layers = mapStyle.Layers;
            layerTreeView.Reload();
            layerTreeView.OnGUI(GUILayoutUtility.GetRect(0, 500, 0, 150));

            var selectedLayers = layerTreeView.GetSelection();

            var layerArrayProperty = serializedObject.FindProperty("Layers");

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add Layer"))
            {
                mapStyle.Layers.Add(new FeatureLayer("untitled"));
            }
            if (GUILayout.Button("Remove Selected"))
            {
                foreach (var index in selectedLayers.OrderByDescending(i => i))
                {
                    layerArrayProperty.DeleteArrayElementAtIndex(index);
                }
                selectedLayers = new int[0];
                layerTreeView.SetSelection(selectedLayers);
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(EditorGUIUtility.singleLineHeight);

            if (selectedLayers.Count == 1)
            {
                var index = selectedLayers[0];

                var layerProperty = layerArrayProperty.GetArrayElementAtIndex(index);

                layerProperty.isExpanded = true;

                GUILayout.Label("Layer Properties", labelBoldStyle);

                var layer = mapStyle.Layers[index];

                layer.FeatureCollection = (FeatureLayer.MapzenFeatureCollection)EditorGUILayout.EnumMaskPopup("Feature Collections", layer.FeatureCollection);

                DrawSelectedLayer(layerProperty);
            }
            else
            {
                GUILayout.Label("Select a layer to see properties", labelItalicCenteredStyle);
            }

            serializedObject.ApplyModifiedProperties();

            if (liveUpdateProperty.boolValue)
            {
                // Find the regionMap containing the style mapStyle
                var       regionMaps = GameObject.FindObjectsOfType <RegionMap>();
                RegionMap map        = null;
                foreach (var regionMap in regionMaps)
                {
                    if (regionMap.Style == mapStyle)
                    {
                        map = regionMap;
                        break;
                    }
                }

                if (map != null)
                {
                    if (GUI.changed)
                    {
                        map.LogWarnings();
                        if (map.IsValid())
                        {
                            map.DownloadTilesAsync();
                        }
                        else
                        {
                            map.LogErrors();
                        }
                    }

                    if (map.HasPendingTasks())
                    {
                        Repaint();
                        if (map.FinishedRunningTasks())
                        {
                            map.GenerateSceneGraph();
                        }
                    }
                }
            }
        }
예제 #29
0
        //While there is a similar method in EditorUtils, due to layouting and especialy no prefix name, this has to be redone a bit differently
        static object VariableField(Variable data, UnityEngine.Object context, GUILayoutOption[] layoutOptions)
        {
            var o = data.value;
            var t = data.varType;

            if (t == typeof(VariableSeperator))
            {
                GUILayout.Space(0);
                return(o);
            }

            //Check scene object type for UnityObjects. Consider Interfaces as scene object type. Assume that user uses interfaces with UnityObjects
            if (typeof(UnityEngine.Object).IsAssignableFrom(t) || t.IsInterface)
            {
                var isSceneObjectType = (typeof(Component).IsAssignableFrom(t) || t == typeof(GameObject) || t.IsInterface);
                return(EditorGUILayout.ObjectField((UnityEngine.Object)o, t, isSceneObjectType, layoutOptions));
            }

            //Check Type second
            if (t == typeof(System.Type))
            {
                return(EditorUtils.Popup <System.Type>(string.Empty, (System.Type)o, UserTypePrefs.GetPreferedTypesList(true), layoutOptions));
            }

            t = o != null?o.GetType() : t;

            if (t.IsAbstract)
            {
                GUILayout.Label(string.Format("({0})", t.FriendlyName()), layoutOptions);
                return(o);
            }

            if (o == null && !t.IsAbstract && !t.IsInterface && (t.GetConstructor(System.Type.EmptyTypes) != null || t.IsArray))
            {
                if (GUILayout.Button("(null) Create", layoutOptions))
                {
                    if (t.IsArray)
                    {
                        return(System.Array.CreateInstance(t.GetElementType(), 0));
                    }
                    return(System.Activator.CreateInstance(t));
                }
                return(o);
            }

            if (t == typeof(bool))
            {
                return(EditorGUILayout.Toggle((bool)o, layoutOptions));
            }

            if (t == typeof(Color))
            {
                return(EditorGUILayout.ColorField((Color)o, layoutOptions));
            }

            if (t == typeof(AnimationCurve))
            {
                return(EditorGUILayout.CurveField((AnimationCurve)o, layoutOptions));
            }

            if (t.IsSubclassOf(typeof(System.Enum)))
            {
                if (t.IsDefined(typeof(System.FlagsAttribute), true))
                {
                    return(EditorGUILayout.EnumMaskPopup(GUIContent.none, (System.Enum)o, layoutOptions));
                }
                return(EditorGUILayout.EnumPopup((System.Enum)o, layoutOptions));
            }

            if (t == typeof(float))
            {
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return(EditorGUILayout.FloatField((float)o, layoutOptions));
            }

            if (t == typeof(int))
            {
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return(EditorGUILayout.IntField((int)o, layoutOptions));
            }

            if (t == typeof(string))
            {
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return(EditorGUILayout.TextField((string)o, layoutOptions));
            }

            if (t == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(string.Empty, (Vector2)o, layoutOptions));
            }

            if (t == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(string.Empty, (Vector3)o, layoutOptions));
            }

            if (t == typeof(Vector4))
            {
                return(EditorGUILayout.Vector4Field(string.Empty, (Vector4)o, layoutOptions));
            }

            if (t == typeof(Quaternion))
            {
                var q = (Quaternion)o;
                var v = new Vector4(q.x, q.y, q.z, q.w);
                v = EditorGUILayout.Vector4Field(string.Empty, v, layoutOptions);
                return(new Quaternion(v.x, v.y, v.z, v.w));
            }

            if (t == typeof(LayerMask))
            {
                return(EditorUtils.LayerMaskField(string.Empty, (LayerMask)o, layoutOptions));
            }

            //If some other type, show it in the generic object editor window
            if (GUILayout.Button(string.Format("{0} {1}", t.FriendlyName(), (o is IList)? ((IList)o).Count.ToString() : string.Empty), layoutOptions))
            {
                GenericInspectorWindow.Show(data.ID, o, t, context);
            }

            //if we are externaly inspecting value and it's this one, get value from the external editor. This is basicaly done for structs
            if (GenericInspectorWindow.current != null && GenericInspectorWindow.current.inspectedID == data.ID)
            {
                return(GenericInspectorWindow.current.value);
            }

            return(o);
        }
예제 #30
0
        //For generic automatic editors. Passing a MemberInfo will also check for attributes
        public static object GenericField(string name, object value, Type t, MemberInfo member = null, object instance = null)
        {
            if (t == null)
            {
                GUILayout.Label("NO TYPE PROVIDED!");
                return(value);
            }

            //Preliminary Hides
            if (typeof(Delegate).IsAssignableFrom(t))
            {
                return(value);
            }

            name = name.SplitCamelCase();

            //

            IEnumerable <Attribute> attributes = new Attribute[0];

            if (member != null)
            {
                //Hide class?
                if (t.GetCustomAttributes(typeof(HideInInspector), true).FirstOrDefault() != null)
                {
                    return(value);
                }

                attributes = member.GetCustomAttributes(true).Cast <Attribute>();

                //Hide field?
                if (attributes.Any(a => a is HideInInspector))
                {
                    return(value);
                }

                //Is required?
                if (attributes.Any(a => a is RequiredFieldAttribute))
                {
                    if ((value == null || value.Equals(null)) ||
                        (t == typeof(string) && string.IsNullOrEmpty((string)value)) ||
                        (typeof(BBParameter).IsAssignableFrom(t) && (value as BBParameter).isNull))
                    {
                        GUI.backgroundColor = lightRed;
                    }
                }
            }


            if (member != null)
            {
                var nameAtt = attributes.FirstOrDefault(a => a is NameAttribute) as NameAttribute;
                if (nameAtt != null)
                {
                    name = nameAtt.name;
                }

                if (instance != null)
                {
                    var showAtt = attributes.FirstOrDefault(a => a is ShowIfAttribute) as ShowIfAttribute;
                    if (showAtt != null)
                    {
                        var targetField = instance.GetType().GetField(showAtt.fieldName);
                        if (targetField == null || targetField.FieldType != typeof(bool))
                        {
                            GUILayout.Label(string.Format("[ShowIf] Error: bool \"{0}\" does not exist.", showAtt.fieldName));
                        }
                        else
                        {
                            if ((bool)targetField.GetValue(instance) != showAtt.show)
                            {
                                return(value);
                            }
                        }
                    }
                }
            }


            //Before everything check BBParameter
            if (typeof(BBParameter).IsAssignableFrom(t))
            {
                return(BBParameterField(name, (BBParameter)value, false, member));
            }


            //Cutstom object drawers
            var objectDrawer = GetCustomDrawer(t);

            if (objectDrawer != null && !(objectDrawer is NoDrawer))
            {
                return(objectDrawer.DrawGUI(name, value, member as FieldInfo, null, instance));
            }

            //Cutstom attribute drawers
            foreach (CustomDrawerAttribute att in attributes.OfType <CustomDrawerAttribute>())
            {
                var attributeDrawer = GetCustomDrawer(att.GetType());
                if (attributeDrawer != null && !(attributeDrawer is NoDrawer))
                {
                    return(attributeDrawer.DrawGUI(name, value, member as FieldInfo, att, instance));
                }
            }


            //Then check UnityObjects
            if (typeof(UnityObject).IsAssignableFrom(t))
            {
                if (t == typeof(Component) && (Component)value != null)
                {
                    return(ComponentField(name, (Component)value, typeof(Component)));
                }
                return(EditorGUILayout.ObjectField(name, (UnityObject)value, t, true));
            }

            //Force UnityObject field?
            if (member != null && attributes.Any(a => a is ForceObjectFieldAttribute))
            {
                return(EditorGUILayout.ObjectField(name, value as UnityObject, t, true));
            }

            //Restricted popup values?
            if (member != null)
            {
                var popAtt = attributes.FirstOrDefault(a => a is PopupFieldAttribute) as PopupFieldAttribute;
                if (popAtt != null)
                {
                    if (popAtt.staticPath != null)
                    {
                        try
                        {
                            var typeName  = popAtt.staticPath.Substring(0, popAtt.staticPath.LastIndexOf("."));
                            var type      = ReflectionTools.GetType(typeName);
                            var start     = popAtt.staticPath.LastIndexOf(".") + 1;
                            var end       = popAtt.staticPath.Length;
                            var propName  = popAtt.staticPath.Substring(start, end - start);
                            var prop      = type.GetProperty(propName, BindingFlags.Static | BindingFlags.Public);
                            var propValue = prop.GetValue(null, null);
                            var values    = ((IEnumerable)propValue).Cast <object>().ToList();
                            return(Popup <object>(name, value, values));
                        }
                        catch
                        {
                            EditorGUILayout.LabelField(name, "[PopupField] attribute error!");
                            return(value);
                        }
                    }
                    return(Popup <object>(name, value, popAtt.values.ToList()));
                }
            }


            //Check Type of Type
            if (t == typeof(Type))
            {
                return(Popup <Type>(name, (Type)value, UserTypePrefs.GetPreferedTypesList(typeof(object), false)));
            }

            //Check abstract
            if ((value != null && value.GetType().IsAbstract) || (value == null && t.IsAbstract))
            {
                EditorGUILayout.LabelField(name, string.Format("Abstract ({0})", t.FriendlyName()));
                return(value);
            }

            //Create instance for some types
            if (value == null && !t.IsAbstract && !t.IsInterface && (t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null || t.IsArray))
            {
                if (t.IsArray)
                {
                    value = Array.CreateInstance(t.GetElementType(), 0);
                }
                else
                {
                    value = Activator.CreateInstance(t);
                }
            }



            //Check the rest
            //..............
            if (t == typeof(string))
            {
                if (member != null)
                {
                    if (attributes.Any(a => a is TagFieldAttribute))
                    {
                        return(EditorGUILayout.TagField(name, (string)value));
                    }
                    var areaAtt = attributes.FirstOrDefault(a => a is TextAreaFieldAttribute) as TextAreaFieldAttribute;
                    if (areaAtt != null)
                    {
                        GUILayout.Label(name);
                        var areaStyle = new GUIStyle(GUI.skin.GetStyle("TextArea"));
                        areaStyle.wordWrap = true;
                        var s = EditorGUILayout.TextArea((string)value, areaStyle, GUILayout.Height(areaAtt.height));
                        return(s);
                    }
                }

                return(EditorGUILayout.TextField(name, (string)value));
            }

            if (t == typeof(bool))
            {
                return(EditorGUILayout.Toggle(name, (bool)value));
            }

            if (t == typeof(int))
            {
                if (member != null)
                {
                    var sField = attributes.FirstOrDefault(a => a is SliderFieldAttribute) as SliderFieldAttribute;
                    if (sField != null)
                    {
                        return((int)EditorGUILayout.Slider(name, (int)value, (int)sField.left, (int)sField.right));
                    }
                    if (attributes.Any(a => a is LayerFieldAttribute))
                    {
                        return(EditorGUILayout.LayerField(name, (int)value));
                    }
                }

                return(EditorGUILayout.IntField(name, (int)value));
            }

            if (t == typeof(float))
            {
                if (member != null)
                {
                    var sField = attributes.FirstOrDefault(a => a is SliderFieldAttribute) as SliderFieldAttribute;
                    if (sField != null)
                    {
                        return(EditorGUILayout.Slider(name, (float)value, sField.left, sField.right));
                    }
                }
                return(EditorGUILayout.FloatField(name, (float)value));
            }

            if (t == typeof(byte))
            {
                return(Convert.ToByte(Mathf.Clamp(EditorGUILayout.IntField(name, (byte)value), 0, 255)));
            }

            if (t == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(name, (Vector2)value));
            }

            if (t == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(name, (Vector3)value));
            }

            if (t == typeof(Vector4))
            {
                return(EditorGUILayout.Vector4Field(name, (Vector4)value));
            }

            if (t == typeof(Quaternion))
            {
                var quat = (Quaternion)value;
                var vec4 = new Vector4(quat.x, quat.y, quat.z, quat.w);
                vec4 = EditorGUILayout.Vector4Field(name, vec4);
                return(new Quaternion(vec4.x, vec4.y, vec4.z, vec4.w));
            }

            if (t == typeof(Color))
            {
                return(EditorGUILayout.ColorField(name, (Color)value));
            }

            if (t == typeof(Rect))
            {
                return(EditorGUILayout.RectField(name, (Rect)value));
            }

            if (t == typeof(AnimationCurve))
            {
                return(EditorGUILayout.CurveField(name, (AnimationCurve)value));
            }

            if (t == typeof(Bounds))
            {
                return(EditorGUILayout.BoundsField(name, (Bounds)value));
            }

            if (t == typeof(LayerMask))
            {
                return(LayerMaskField(name, (LayerMask)value));
            }

            if (t.IsSubclassOf(typeof(System.Enum)))
            {
#if UNITY_5
                if (t.GetCustomAttributes(typeof(FlagsAttribute), true).FirstOrDefault() != null)
                {
                    return(EditorGUILayout.EnumMaskPopup(new GUIContent(name), (System.Enum)value));
                }
#endif
                return(EditorGUILayout.EnumPopup(name, (System.Enum)value));
            }

            if (typeof(IList).IsAssignableFrom(t))
            {
                return(ListEditor(name, (IList)value, t, instance));
            }

            if (typeof(IDictionary).IsAssignableFrom(t))
            {
                return(DictionaryEditor(name, (IDictionary)value, t, instance));
            }


            //show nested class members recursively
            if (value != null && !t.IsEnum && !t.IsInterface)
            {
                GUILayout.BeginVertical();
                EditorGUILayout.LabelField(name, t.FriendlyName());
                EditorGUI.indentLevel++;
                ShowAutoEditorGUI(value);
                EditorGUI.indentLevel--;
                GUILayout.EndVertical();
            }
            else
            {
                EditorGUILayout.LabelField(name, string.Format("({0})", t.FriendlyName()));
            }

            return(value);
        }