// On inspector gui
	public override void OnInspectorGUI( )
	{	
		Uni2DTextureAtlas rAtlas = target as Uni2DTextureAtlas;
		
		EditorGUIUtility.LookLikeInspector( );

		// Material override
		EditorGUILayout.BeginVertical( );
		{
			rAtlas.materialOverride = (Material) EditorGUILayout.ObjectField( "Material Override", rAtlas.materialOverride, typeof( Material ), false );
			rAtlas.maximumAtlasSize = (AtlasSize) EditorGUILayout.EnumPopup( "Maximum Atlas Size", rAtlas.maximumAtlasSize );

			rAtlas.padding = EditorGUILayout.IntField( "Padding", rAtlas.padding );
			rAtlas.padding = Mathf.Abs( rAtlas.padding );

			// Texture to pack list
			// Custom list GUI: displays Texture2D objects, handles asset GUIDs		
			serializedObject.Update( );
			SerializedProperty rSerializedProperty_Textures = serializedObject.FindProperty( "textures" );
			int iContainerIndex = 0;

			EditorGUILayout.Space( );

	    	while( true )
			{
				string oPropertyPath = rSerializedProperty_Textures.propertyPath;
				string oPropertyName = rSerializedProperty_Textures.name;
				bool bIsTextureContainer = oPropertyPath.Contains( "textures" );
	
				// Indent
				EditorGUI.indentLevel = rSerializedProperty_Textures.depth;
				
				if( bIsTextureContainer )
				{
					if( oPropertyName == "textures" )
					{
						GUIContent oGUIContentTexturesLabel = new GUIContent( "Textures" );
						Rect rFoldoutRect   = GUILayoutUtility.GetRect( oGUIContentTexturesLabel, EditorStyles.foldout );
						Event rCurrentEvent = Event.current;

						switch( rCurrentEvent.type )
						{
							// Drag performed
							case EventType.DragPerform:
							{
								// Check if dragged objects are inside the foldout rect
								if( rFoldoutRect.Contains( rCurrentEvent.mousePosition ) )
								{
									// Accept and use the event
									DragAndDrop.AcceptDrag( );
									rCurrentEvent.Use( );

									EditorGUIUtility.hotControl = 0;
									DragAndDrop.activeControlID = 0;

									// Add the textures to the current list
									foreach( Object rDraggedObject in DragAndDrop.objectReferences )
									{
										if( rDraggedObject is Texture2D )
										{
											int iCurrentSize = rSerializedProperty_Textures.arraySize;
											++rSerializedProperty_Textures.arraySize;
											SerializedProperty rSerializedProperty_Data = rSerializedProperty_Textures.GetArrayElementAtIndex( iCurrentSize );
											rSerializedProperty_Data = rSerializedProperty_Data.FindPropertyRelative( "m_oTextureGUID" );

											rSerializedProperty_Data.stringValue = rDraggedObject != null
												? Uni2DEditorUtils.GetUnityAssetGUID( (Texture2D) rDraggedObject )
												: null;
										}
									}
								}
							}
							break;

							case EventType.DragUpdated:
							{
								if( rFoldoutRect.Contains( rCurrentEvent.mousePosition ) )
								{
									DragAndDrop.visualMode = DragAndDropVisualMode.Copy;						
								}
							}
							break;
						}
						EditorGUI.indentLevel = 0;
						ms_bTexturesFoldout = EditorGUI.Foldout( rFoldoutRect, ms_bTexturesFoldout, oGUIContentTexturesLabel );
					}
					else if( oPropertyName == "data" )
					{
						SerializedProperty rSerializedProperty_TextureGUID = rSerializedProperty_Textures.FindPropertyRelative( "m_oTextureGUID" );
						Texture2D rTexture = Uni2DEditorUtils.GetAssetFromUnityGUID<Texture2D>( rSerializedProperty_TextureGUID.stringValue );
		
						EditorGUI.BeginChangeCheck( );
						{
							rTexture = (Texture2D) EditorGUILayout.ObjectField( "Element " + iContainerIndex, rTexture, typeof( Texture2D ), false );
							++iContainerIndex;
						}
						if( EditorGUI.EndChangeCheck( ) )
						{
							rSerializedProperty_TextureGUID.stringValue = rTexture != null
								? Uni2DEditorUtils.GetUnityAssetGUID( rTexture )
								: null;
						}
					}
					else 
					{
						// Default draw of the property field
						EditorGUILayout.PropertyField( rSerializedProperty_Textures );
					}
				}
	
				if( rSerializedProperty_Textures.NextVisible( ms_bTexturesFoldout ) == false )
				{
					break;
				}
			}
	
			serializedObject.ApplyModifiedProperties( );

			EditorGUILayout.Space( );

			EditorGUI.indentLevel = 0;

			///// Generated assets section /////
	
			// Materials
			ms_bGeneratedMaterialsFoldout = EditorGUILayout.Foldout( ms_bGeneratedMaterialsFoldout, "Generated Materials" );
			if( ms_bGeneratedMaterialsFoldout )
			{
				++EditorGUI.indentLevel;
				{
					if( ms_oAtlasMaterials.Length > 0 )
					{
						foreach( Material rAtlasMaterial in ms_oAtlasMaterials )
						{
							EditorGUILayout.BeginHorizontal( );
							{
								GUILayout.Space( 16.0f );
								if( GUILayout.Button( EditorGUIUtility.ObjectContent( rAtlasMaterial, typeof( Material ) ), EditorStyles.label, GUILayout.ExpandWidth( false ), GUILayout.MaxWidth( 225.0f ), GUILayout.MaxHeight( 16.0f ) ) )
								{
									EditorGUIUtility.PingObject( rAtlasMaterial );
								}
							}
							EditorGUILayout.EndHorizontal( );
						}
					}
					else
					{
						EditorGUILayout.PrefixLabel( "(None)" );
					}
				}
				--EditorGUI.indentLevel;
			}

			EditorGUILayout.Space( );

			// Atlas textures
			ms_bGeneratedTexturesFoldout = EditorGUILayout.Foldout( ms_bGeneratedTexturesFoldout, "Generated Textures" );
			if( ms_bGeneratedTexturesFoldout )
			{
				++EditorGUI.indentLevel;
				{
					if( ms_oAtlasTextures.Length > 0 )
					{
						foreach( Texture2D rAtlasTexture in ms_oAtlasTextures )
						{
							EditorGUILayout.BeginHorizontal( );
							{
								GUILayout.Space( 16.0f );
								if( GUILayout.Button( EditorGUIUtility.ObjectContent( rAtlasTexture, typeof( Texture2D ) ), EditorStyles.label, GUILayout.ExpandWidth( false ), GUILayout.MaxWidth( 225.0f ), GUILayout.MaxHeight( 16.0f ) ) )
								{
									EditorGUIUtility.PingObject( rAtlasTexture );
								}
							}
							EditorGUILayout.EndHorizontal( );
						}
					}
					else
					{
						EditorGUILayout.PrefixLabel( "(None)" );
					}
				}
				--EditorGUI.indentLevel;
			}

			bool bUnappliedSettings = rAtlas.UnappliedSettings;
			EditorGUI.BeginDisabledGroup( bUnappliedSettings == false );
			{
				// Apply/Revert
				EditorGUILayout.BeginHorizontal( );
				{
					if(GUILayout.Button( "Apply" ) )
					{
						this.ApplySettings( );
					}
					
					if( GUILayout.Button( "Revert" ) )
					{
						rAtlas.RevertSettings( );
					}
				}
				EditorGUILayout.EndHorizontal( );
			}
			EditorGUI.EndDisabledGroup();

			// Generate
			if( GUILayout.Button( "Force atlas regeneration" ) )
			{
				this.ApplySettings( );
			}
		}
		EditorGUILayout.EndVertical( );
	}
        //Draws a popup showing the available plugins for the project
        private void DrawAddConverterPopup(Rect position)
        {
            var ROLDefaults = new ReorderableList.Defaults();
            var padding     = 4f;

            _availablePlugins = DynamicDNAPlugin.GetAvailablePluginTypes();

            Rect addRect = Rect.zero;

            if (position == Rect.zero)
            {
                GUILayout.BeginVertical(_pluginChooserAreaStyle);
                addRect = EditorGUILayout.GetControlRect();
            }
            else
            {
                addRect = position;
            }
            addRect.xMin = addRect.xMax - 190 > addRect.xMin ? addRect.xMax - 190 : addRect.xMin;
            var labelRect    = new Rect(addRect.xMin + (padding * 2), addRect.yMin, addRect.width - (padding * 2), 0);
            var addPopupRect = new Rect(addRect.xMin + (padding * 2), labelRect.yMax, addRect.width - _addPluginBtnWidth - (padding * 2), EditorGUIUtility.singleLineHeight);
            var addBtnRect   = new Rect(addPopupRect.xMax + padding, labelRect.yMax, _addPluginBtnWidth - (padding * 3), EditorGUIUtility.singleLineHeight);

            if (Event.current.type == EventType.Repaint)
            {
                var prevFooterFixedHeight = ROLDefaults.footerBackground.fixedHeight;
                ROLDefaults.footerBackground.fixedHeight = addRect.height;
                ROLDefaults.footerBackground.Draw(addRect, false, false, false, false);
                ROLDefaults.footerBackground.fixedHeight = prevFooterFixedHeight;
            }

            var dropdownLabel = _pluginToAdd != null ? _pluginToAdd.Name : "Add Converters...";

            if (EditorGUI.DropdownButton(addPopupRect, new GUIContent(dropdownLabel, "Add converters of the selected type to the " + _dnaConvertersLabel + " list"), FocusType.Keyboard))
            {
                // create the menu and add items to it
                GenericMenu popupMenu = new GenericMenu();

                //add the choose entry- clears the selection
                AddMenuItemForAddConvertersPopup(popupMenu, null);

                //add the actual entries
                for (int i = 0; i < _availablePlugins.Count; i++)
                {
                    AddMenuItemForAddConvertersPopup(popupMenu, _availablePlugins[i]);
                }

                // display the menu
                popupMenu.DropDown(addPopupRect);
            }

            EditorGUI.BeginDisabledGroup(_pluginToAdd == null);
            if (GUI.Button(addBtnRect, new GUIContent("Add", (_pluginToAdd == null ? "Choose converters to add first" : ""))))
            {
                //do it!
                _target.AddPlugin(_pluginToAdd);
                //reset the choice
                _pluginToAdd = null;
                //reInit the plugins
                InitPlugins();
            }
            EditorGUI.EndDisabledGroup();

            if (position == Rect.zero)
            {
                GUILayout.EndVertical();
            }
        }
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        if (mLastAtlas != NGUISettings.atlas)
        {
            mLastAtlas = NGUISettings.atlas;
        }

        bool update  = false;
        bool replace = false;

        NGUIEditorTools.SetLabelWidth(80f);
        GUILayout.Space(3f);

        NGUIEditorTools.DrawHeader("Input");
        NGUIEditorTools.BeginContents();

        GUILayout.BeginHorizontal();
        {
            ComponentSelector.Draw <UIAtlas>("Atlas", NGUISettings.atlas, OnSelectAtlas, true, GUILayout.MinWidth(80f));

            //EditorGUI.BeginDisabledGroup(NGUISettings.atlas == null);
            //if (GUILayout.Button("New", GUILayout.Width(40f)))
            //    NGUISettings.atlas = null;
            //EditorGUI.EndDisabledGroup();
        }
        GUILayout.EndHorizontal();

        List <Texture> textures = GetSelectedTextures();

        if (NGUISettings.atlas != null)
        {
            Material mat = NGUISettings.atlas.spriteMaterial;
            Texture  tex = NGUISettings.atlas.texture;

            // Material information
            GUILayout.BeginHorizontal();
            {
                if (mat != null)
                {
                    if (GUILayout.Button("Material", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = mat;
                    }
                    GUILayout.Label(" " + mat.name);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Material", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();

            // Texture atlas information
            GUILayout.BeginHorizontal();
            {
                if (tex != null)
                {
                    if (GUILayout.Button("Texture", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = tex;
                    }
                    GUILayout.Label(" " + tex.width + "x" + tex.height);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Texture", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();
        }

        GUILayout.BeginHorizontal();
        NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
        GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " between sprites");
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
        GUILayout.Label("Remove empty space");
        GUILayout.EndHorizontal();

        bool fixedShader = false;

        if (NGUISettings.atlas != null)
        {
            Material mat = NGUISettings.atlas.spriteMaterial;

            if (mat != null)
            {
                Shader shader = mat.shader;

                if (shader != null)
                {
                    if (shader.name == "Unlit/Transparent Colored")
                    {
                        NGUISettings.atlasPMA = false;
                        fixedShader           = true;
                    }
                    else if (shader.name == "Unlit/Premultiplied Colored")
                    {
                        NGUISettings.atlasPMA = true;
                        fixedShader           = true;
                    }
                }
            }
        }

        if (!fixedShader)
        {
            GUILayout.BeginHorizontal();
            NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
            GUILayout.Label("Pre-multiplied alpha", GUILayout.MinWidth(70f));
            GUILayout.EndHorizontal();
        }

        GUILayout.BeginHorizontal();
        NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
        GUILayout.Label("or custom packer", GUILayout.MinWidth(70f));
        GUILayout.EndHorizontal();

        if (!NGUISettings.unityPacking)
        {
            GUILayout.BeginHorizontal();
            NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
            GUILayout.Label("if on, forces a square atlas texture", GUILayout.MinWidth(70f));
            GUILayout.EndHorizontal();
        }

#if UNITY_IPHONE || UNITY_ANDROID
        GUILayout.BeginHorizontal();
        NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
        GUILayout.Label("if off, limit atlases to 2048x2048");
        GUILayout.EndHorizontal();
#endif
        NGUIEditorTools.EndContents();

        if (NGUISettings.atlas != null)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(20f);

            if (textures.Count > 0)
            {
                update = GUILayout.Button("Add/Update");
            }
            else if (GUILayout.Button("View Sprites"))
            {
                SpriteSelector.ShowSelected();
            }

            GUILayout.Space(20f);
            GUILayout.EndHorizontal();
        }
        else
        {
            EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);

            EditorGUI.BeginDisabledGroup(textures.Count == 0);
            GUILayout.BeginHorizontal();
            GUILayout.Space(20f);
            bool create = GUILayout.Button("Create");
            GUILayout.Space(20f);
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            if (create)
            {
                string prefabPath = EditorUtility.SaveFilePanelInProject("Save As", "New Atlas.prefab", "prefab", "Save atlas as...");

                if (!string.IsNullOrEmpty(prefabPath))
                {
                    GameObject go      = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    string     matPath = prefabPath.Replace(".prefab", ".mat");
                    replace = true;

                    // Try to load the material
                    Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }

                    // Create a new prefab for the atlas
                    Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(prefabPath);

                    // Create a new game object for the atlas
                    string atlasName = prefabPath.Replace(".prefab", "");
                    atlasName = atlasName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
                    go        = new GameObject(atlasName);
                    go.AddComponent <UIAtlas>().spriteMaterial = mat;

                    // Update the prefab
                    PrefabUtility.ReplacePrefab(go, prefab);
                    DestroyImmediate(go);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                    // Select the atlas
                    go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    NGUISettings.atlas         = go.GetComponent <UIAtlas>();
                    Selection.activeGameObject = go;
                }
            }
        }

        string selection = null;
        Dictionary <string, int> spriteList = GetSpriteList(textures);

        if (spriteList.Count > 0)
        {
            NGUIEditorTools.DrawHeader("Sprites", true);
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(3f);
                GUILayout.BeginVertical();

                mScroll = GUILayout.BeginScrollView(mScroll);

                bool delete = false;
                int  index  = 0;
                foreach (KeyValuePair <string, int> iter in spriteList)
                {
                    ++index;

                    GUILayout.Space(-1f);
                    bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
                    GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
                    GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                    GUI.backgroundColor = Color.white;
                    GUILayout.Label(index.ToString(), GUILayout.Width(24f));

                    if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
                    {
                        selection = iter.Key;
                    }

                    if (iter.Value == 2)
                    {
                        GUI.color = Color.green;
                        GUILayout.Label("Add", GUILayout.Width(27f));
                        GUI.color = Color.white;
                    }
                    else if (iter.Value == 1)
                    {
                        GUI.color = Color.cyan;
                        GUILayout.Label("Update", GUILayout.Width(45f));
                        GUI.color = Color.white;
                    }
                    else
                    {
                        if (mDelNames.Contains(iter.Key))
                        {
                            GUI.backgroundColor = Color.red;

                            if (GUILayout.Button("Delete", GUILayout.Width(60f)))
                            {
                                delete = true;
                            }
                            GUI.backgroundColor = Color.green;
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Remove(iter.Key);
                                delete = false;
                            }
                            GUI.backgroundColor = Color.white;
                        }
                        else
                        {
                            // If we have not yet selected a sprite for deletion, show a small "X" button
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Add(iter.Key);
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndScrollView();
                GUILayout.EndVertical();
                GUILayout.Space(3f);
                GUILayout.EndHorizontal();

                // If this sprite was marked for deletion, remove it from the atlas
                if (delete)
                {
                    List <SpriteEntry> sprites = new List <SpriteEntry>();
                    ExtractSprites(NGUISettings.atlas, sprites);

                    for (int i = sprites.Count; i > 0;)
                    {
                        SpriteEntry ent = sprites[--i];
                        if (mDelNames.Contains(ent.name))
                        {
                            sprites.RemoveAt(i);
                        }
                    }
                    UpdateAtlas(NGUISettings.atlas, sprites);
                    mDelNames.Clear();
                    NGUIEditorTools.RepaintSprites();
                }
                else if (update)
                {
                    UpdateAtlas(textures, true);
                }
                else if (replace)
                {
                    UpdateAtlas(textures, false);
                }

                if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
                {
                    NGUIEditorTools.SelectSprite(selection);
                }
                else if (update || replace)
                {
                    NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
                    NGUIEditorTools.RepaintSprites();
                }
            }
        }

        if (NGUISettings.atlas != null && textures.Count == 0)
        {
            EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);
        }

        // Uncomment this line if you want to be able to force-sort the atlas
        //if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
    }
        public override void DrawProperties()
        {
            base.DrawProperties();

            EditorGUI.BeginChangeCheck();
            m_selectedChannelInt = EditorGUILayoutPopup("Channel", m_selectedChannelInt, m_channelTypeStr);
            if (EditorGUI.EndChangeCheck())
            {
                UpdateSampler();
                GeneratePOMfunction();
            }
            EditorGUIUtility.labelWidth = 105;

            m_minSamples = EditorGUILayoutIntSlider("Min Samples", m_minSamples, 1, 128);
            m_maxSamples = EditorGUILayoutIntSlider("Max Samples", m_maxSamples, 1, 128);

            EditorGUI.BeginChangeCheck();
            m_sidewallSteps = EditorGUILayoutIntSlider("Sidewall Steps", m_sidewallSteps, 0, 10);
            if (EditorGUI.EndChangeCheck())
            {
                GeneratePOMfunction();
            }


            EditorGUI.BeginDisabledGroup(m_scalePort.IsConnected);
            m_defaultScale = EditorGUILayoutSlider("Default Scale", m_defaultScale, 0, 1);
            EditorGUI.EndDisabledGroup();

            EditorGUI.BeginDisabledGroup(m_refPlanePort.IsConnected);
            m_defaultRefPlane = EditorGUILayoutSlider("Default Ref Plane", m_defaultRefPlane, 0, 1);
            EditorGUI.EndDisabledGroup();
            EditorGUIUtility.labelWidth = m_textLabelWidth;
            EditorGUI.BeginChangeCheck();
            //m_useTextureArray = EditorGUILayoutToggle( "Use Texture Array", m_useTextureArray );
            m_pomTexType = (POMTexTypes)EditorGUILayoutEnumPopup("Texture Type", m_pomTexType);
            if (EditorGUI.EndChangeCheck())
            {
                UpdateIndexPort();
                m_sizeIsDirty = true;
                GeneratePOMfunction();
                //UpdateCurvaturePort();
            }

            if (m_arrayIndexPort.Visible && !m_arrayIndexPort.IsConnected)
            {
                m_arrayIndexPort.FloatInternalData = EditorGUILayoutFloatField("Array Index", m_arrayIndexPort.FloatInternalData);
            }

            //float cached = EditorGUIUtility.labelWidth;
            //EditorGUIUtility.labelWidth = 70;
            m_clipEnds = EditorGUILayoutToggle("Clip Edges", m_clipEnds);
            //EditorGUIUtility.labelWidth = -1;
            //EditorGUIUtility.labelWidth = 100;
            //EditorGUILayout.BeginHorizontal();
            //EditorGUI.BeginDisabledGroup( !m_clipEnds );
            //m_tilling = EditorGUILayout.Vector2Field( string.Empty, m_tilling );
            //EditorGUI.EndDisabledGroup();
            //EditorGUILayout.EndHorizontal();
            //EditorGUIUtility.labelWidth = cached;

            EditorGUI.BeginChangeCheck();
            m_useCurvature = EditorGUILayoutToggle("Clip Silhouette", m_useCurvature);
            if (EditorGUI.EndChangeCheck())
            {
                GeneratePOMfunction();
                UpdateCurvaturePort();
            }

            EditorGUI.BeginDisabledGroup(!(m_useCurvature && !m_curvaturePort.IsConnected));
            m_CurvatureVector = EditorGUILayoutVector2Field(string.Empty, m_CurvatureVector);
            EditorGUI.EndDisabledGroup();

            EditorGUILayout.HelpBox("Min and Max samples:\nControl the minimum and maximum number of layers extruded\n\nSidewall Steps:\nThe number of interpolations done to smooth the extrusion result on the side of the layer extrusions, min is used at steep angles while max is used at orthogonal angles\n\n" +
                                    "Ref Plane:\nReference plane lets you adjust the starting reference height, 0 = deepen ground, 1 = raise ground, any value above 0 might cause distortions at higher angles\n\n" +
                                    "Clip Edges:\nThis will clip the ends of your uvs to give a more 3D look at the edges. It'll use the tilling given by your Heightmap input.\n\n" +
                                    "Clip Silhouette:\nTurning this on allows you to use the UV coordinates to clip the effect curvature in U or V axis, useful for cylinders, works best with 'Clip Edges' turned OFF", MessageType.None);
        }
        public void OnGUI()
        {
            // scroll view of settings
            EditorGUIUtility.hierarchyMode = true;
            TerrainToolboxUtilities.DrawSeperatorLine();
            m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);

            // General Settings
            ShowGeneralGUI();

            // Import Heightmap
            TerrainToolboxUtilities.DrawSeperatorLine();
            bool importHeightmapToggle = m_Settings.EnableHeightmapImport;

            m_Settings.ShowHeightmapSettings = TerrainToolGUIHelper.DrawToggleHeaderFoldout(Styles.ImportHeightmap, m_Settings.ShowHeightmapSettings, ref importHeightmapToggle, 0f);
            ++EditorGUI.indentLevel;
            if (m_Settings.ShowHeightmapSettings)
            {
                EditorGUI.BeginDisabledGroup(!m_Settings.EnableHeightmapImport);
                ShowImportHeightmapGUI();
                EditorGUI.EndDisabledGroup();
            }
            m_Settings.EnableHeightmapImport = importHeightmapToggle;

            // Presets
            ShowPresetGUI();

            // Gizmos
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(Styles.Gizmo, EditorStyles.boldLabel);
            if (GUILayout.Button(Styles.ShowGizmo))
            {
                ToolboxHelper.ShowGizmo();
            }
            if (GUILayout.Button(Styles.HideGizmo))
            {
                ToolboxHelper.HideGizmo();
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();
            EditorGUILayout.EndScrollView();

            // Options
            ShowOptionsGUI();

            // Terrain info box
            --EditorGUI.indentLevel;
            string sizeMsg     = string.Format("Terrain Size: {0}m x {1}m		", m_Settings.TerrainWidth, m_Settings.TerrainLength);
            string tileMsg     = string.Format("Number of Tiles: {0} x {1} \n", m_Settings.TilesX, m_Settings.TilesZ);
            string heightMsg   = string.Format("Terrain Height: {0}m		", m_Settings.TerrainHeight);
            string tileSizeMsg = string.Format("Tile Size: {0} x {1} ", (m_Settings.TerrainWidth / m_Settings.TilesX), (m_Settings.TerrainLength / m_Settings.TilesZ));

            m_TerrainMessage = sizeMsg + tileMsg + heightMsg + tileSizeMsg;
            EditorGUILayout.HelpBox(m_TerrainMessage, MessageType.Info);

            // Create
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(Styles.CreateBtn, GUILayout.Height(40)))
            {
                if (!RunCreateValidations())
                {
                    EditorUtility.DisplayDialog("Error", "There are incompatible terrain creation settings that need to be resolved to continue. Please check Console for details.", "OK");
                }
                else
                {
                    if (m_Settings.HeightmapMode == Heightmap.Mode.Global && File.Exists(m_Settings.GlobalHeightmapPath))
                    {
                        m_Settings.UseGlobalHeightmap = true;
                    }
                    else
                    {
                        m_Settings.UseGlobalHeightmap = false;
                    }

                    Create();
                }
            }
            EditorGUILayout.EndHorizontal();
        }
Пример #6
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            serializedObject.Update();

            BaseComponent t = (BaseComponent)target;

            EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
            {
                m_EditorResourceMode.boolValue = EditorGUILayout.BeginToggleGroup("Editor Resource Mode", m_EditorResourceMode.boolValue);
                {
                    EditorGUILayout.HelpBox("Editor resource mode option is only for editor mode. Game Framework will use editor resource files, which you should validate first.", MessageType.Warning);
                    EditorGUILayout.PropertyField(m_EditorLanguage);
                    EditorGUILayout.HelpBox("Editor language option is only use for localization test in editor mode.", MessageType.Info);
                }
                EditorGUILayout.EndToggleGroup();

                EditorGUILayout.BeginVertical("box");
                {
                    EditorGUILayout.LabelField("Global Helpers", EditorStyles.boldLabel);

                    int versionHelperSelectedIndex = EditorGUILayout.Popup("Version Helper", m_VersionHelperTypeNameIndex, m_VersionHelperTypeNames);
                    if (versionHelperSelectedIndex != m_VersionHelperTypeNameIndex)
                    {
                        m_VersionHelperTypeNameIndex        = versionHelperSelectedIndex;
                        m_VersionHelperTypeName.stringValue = (versionHelperSelectedIndex <= 0 ? null : m_VersionHelperTypeNames[versionHelperSelectedIndex]);
                    }

                    int logHelperSelectedIndex = EditorGUILayout.Popup("Log Helper", m_LogHelperTypeNameIndex, m_LogHelperTypeNames);
                    if (logHelperSelectedIndex != m_LogHelperTypeNameIndex)
                    {
                        m_LogHelperTypeNameIndex        = logHelperSelectedIndex;
                        m_LogHelperTypeName.stringValue = (logHelperSelectedIndex <= 0 ? null : m_LogHelperTypeNames[logHelperSelectedIndex]);
                    }

                    int zipHelperSelectedIndex = EditorGUILayout.Popup("Zip Helper", m_ZipHelperTypeNameIndex, m_ZipHelperTypeNames);
                    if (zipHelperSelectedIndex != m_ZipHelperTypeNameIndex)
                    {
                        m_ZipHelperTypeNameIndex        = zipHelperSelectedIndex;
                        m_ZipHelperTypeName.stringValue = (zipHelperSelectedIndex <= 0 ? null : m_ZipHelperTypeNames[zipHelperSelectedIndex]);
                    }

                    int jsonHelperSelectedIndex = EditorGUILayout.Popup("JSON Helper", m_JsonHelperTypeNameIndex, m_JsonHelperTypeNames);
                    if (jsonHelperSelectedIndex != m_JsonHelperTypeNameIndex)
                    {
                        m_JsonHelperTypeNameIndex        = jsonHelperSelectedIndex;
                        m_JsonHelperTypeName.stringValue = (jsonHelperSelectedIndex <= 0 ? null : m_JsonHelperTypeNames[jsonHelperSelectedIndex]);
                    }

                    int profilerHelperSelectedIndex = EditorGUILayout.Popup("Profiler Helper", m_ProfilerHelperTypeNameIndex, m_ProfilerHelperTypeNames);
                    if (profilerHelperSelectedIndex != m_ProfilerHelperTypeNameIndex)
                    {
                        m_ProfilerHelperTypeNameIndex        = profilerHelperSelectedIndex;
                        m_ProfilerHelperTypeName.stringValue = (profilerHelperSelectedIndex <= 0 ? null : m_ProfilerHelperTypeNames[profilerHelperSelectedIndex]);
                    }
                }
                EditorGUILayout.EndVertical();
            }
            EditorGUI.EndDisabledGroup();

            int frameRate = EditorGUILayout.IntSlider("Frame Rate", m_FrameRate.intValue, 1, 120);

            if (frameRate != m_FrameRate.intValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.FrameRate = frameRate;
                }
                else
                {
                    m_FrameRate.intValue = frameRate;
                }
            }

            EditorGUILayout.BeginVertical("box");
            {
                float gameSpeed         = EditorGUILayout.Slider("Game Speed", m_GameSpeed.floatValue, 0f, 8f);
                int   selectedGameSpeed = GUILayout.SelectionGrid(GetSelectedGameSpeed(gameSpeed), GameSpeedTexts, 5);
                if (selectedGameSpeed >= 0)
                {
                    gameSpeed = GetGameSpeed(selectedGameSpeed);
                }

                if (gameSpeed != m_GameSpeed.floatValue)
                {
                    if (EditorApplication.isPlaying)
                    {
                        t.GameSpeed = gameSpeed;
                    }
                    else
                    {
                        m_GameSpeed.floatValue = gameSpeed;
                    }
                }
            }
            EditorGUILayout.EndVertical();

            bool runInBackground = EditorGUILayout.Toggle("Run in Background", m_RunInBackground.boolValue);

            if (runInBackground != m_RunInBackground.boolValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.RunInBackground = runInBackground;
                }
                else
                {
                    m_RunInBackground.boolValue = runInBackground;
                }
            }

            bool neverSleep = EditorGUILayout.Toggle("Never Sleep", m_NeverSleep.boolValue);

            if (neverSleep != m_NeverSleep.boolValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.NeverSleep = neverSleep;
                }
                else
                {
                    m_NeverSleep.boolValue = neverSleep;
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
        private void DrawLinks(IEnumerable <ThingInMemory> thingInMemories, int bIsReferences)
        {
            var   c = GUI.backgroundColor;
            Color elementColor;

            if (bIsReferences == 1)
            {
                elementColor = Color.white;
            }
            else if (bIsReferences == 2)
            {
                elementColor = new Color(0.8039f, 0.8627f, 0.2235f);
            }
            else
            {
                elementColor = new Color(0, 0.8f, 0.8f);
            }
            GUI.skin.button.alignment = TextAnchor.UpperLeft;
            foreach (var thingInMemory in thingInMemories)
            {
                bool disableGroup = thingInMemory == myInfo.memObject || thingInMemory == null;
                if (bCreateChildNodes)
                {
                    if (referencesNum < thingInMemories.Count <ThingInMemory>())
                    {
                        if (!disableGroup)
                        {
                            CreateChildNodes(thingInMemory, elementColor);
                            referencesNum++;
                        }
                    }
                }

                {
                    EditorGUI.BeginDisabledGroup(disableGroup);

                    GUI.backgroundColor = ColorFor(thingInMemory);

                    var caption = thingInMemory == null ? "null" : thingInMemory.caption;

                    var managedObject = thingInMemory as ManagedObject;
                    if (managedObject != null && managedObject.typeDescription.name == "System.String")
                    {
                        caption = StringTools.ReadString(_unpackedCrawl.managedHeap.Find(managedObject.address, _unpackedCrawl.virtualMachineInformation), _unpackedCrawl.virtualMachineInformation);
                    }

                    if (GUILayout.Button(caption))
                    {
                        var nativeObject = thingInMemory as NativeUnityEngineObject;
                        if (nativeObject != null)
                        {
                            int nodeId = parent.FindExistingObjectByInstanceID(nativeObject.instanceID);
                            if (nodeId < 0)
                            {
                                if (!disableGroup)
                                {
                                    CreateChildNodes(thingInMemory, elementColor, false);
                                }
                            }
                            else
                            {
                                parent.SetSelectedNode(nodeId);
                            }
                        }
                        var manObject = thingInMemory as ManagedObject;
                        if (manObject != null)
                        {
                            if (!disableGroup)
                            {
                                int nodeId = parent.FindExistingObjectByAddress(manObject.address);
                                if (nodeId < 0)
                                {
                                    CreateChildNodes(thingInMemory, elementColor, false);
                                }
                                else
                                {
                                    parent.SetSelectedNode(nodeId);
                                }
                            }
                        }
                        if (thingInMemory is GCHandle)
                        {
                            if (!disableGroup)
                            {
                                CreateChildNodes(thingInMemory, elementColor, false);
                            }
                        }
                        var staticFields = thingInMemory as StaticFields;
                        if (staticFields != null)
                        {
                            if (!disableGroup)
                            {
                                CreateChildNodes(thingInMemory, elementColor, false);
                            }
                        }
                    }
                    EditorGUI.EndDisabledGroup();
                }
            }
            GUI.backgroundColor = c;
        }
Пример #8
0
    /// @cond
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // Add clickable script field, as would have been provided by DrawDefaultInspector()
        MonoScript script = MonoScript.FromMonoBehaviour(target as MonoBehaviour);

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false);
        EditorGUI.EndDisabledGroup();

        EditorGUILayout.PropertyField(clip, clipLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(mute, muteLabel);
        EditorGUILayout.PropertyField(bypassRoomEffects, bypassRoomEffectsLabel);
        EditorGUILayout.PropertyField(playOnAwake, playOnAwakeLabel);
        EditorGUILayout.PropertyField(loop, loopLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(priority, priorityLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(volume, volumeLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(pitch, pitchLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(spatialBlend, spatialBlendLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.Slider(gainDb, GvrAudio.minGainDb, GvrAudio.maxGainDb, gainLabel);

        EditorGUILayout.Separator();

        EditorGUILayout.PropertyField(dopplerLevel, dopplerLevelLabel);
        EditorGUILayout.PropertyField(spread, spreadLabel);
        EditorGUILayout.PropertyField(rolloffMode, rolloffModeLabel);
        ++EditorGUI.indentLevel;
        EditorGUILayout.PropertyField(minDistance, minDistanceLabel);
        EditorGUILayout.PropertyField(maxDistance, maxDistanceLabel);
        --EditorGUI.indentLevel;
        if (rolloffMode.enumValueIndex == (int)AudioRolloffMode.Custom)
        {
            EditorGUILayout.HelpBox("Custom rolloff mode is not supported, no distance attenuation " +
                                    "will be applied.", MessageType.Warning);
        }

        EditorGUILayout.Separator();

        // Draw the listener directivity properties.
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical();
        GUILayout.Label(listenerDirectivityLabel);
        ++EditorGUI.indentLevel;
        EditorGUILayout.Slider(listenerDirectivityAlpha, 0.0f, 1.0f, listenerDirectivityAlphaLabel);
        EditorGUILayout.Slider(listenerDirectivitySharpness, 1.0f, 10.0f,
                               listenerDirectivitySharpnessLabel);
        --EditorGUI.indentLevel;
        EditorGUILayout.EndVertical();
        DrawDirectivityPattern(listenerDirectivityAlpha.floatValue,
                               listenerDirectivitySharpness.floatValue,
                               GvrAudio.listenerDirectivityColor,
                               (int)(3.0f * EditorGUIUtility.singleLineHeight));
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Separator();

        // Draw the source directivity properties.
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical();
        GUILayout.Label(directivityLabel);
        ++EditorGUI.indentLevel;
        EditorGUILayout.Slider(directivityAlpha, 0.0f, 1.0f, directivityAlphaLabel);
        EditorGUILayout.Slider(directivitySharpness, 1.0f, 10.0f, directivitySharpnessLabel);
        --EditorGUI.indentLevel;
        EditorGUILayout.EndVertical();
        DrawDirectivityPattern(directivityAlpha.floatValue, directivitySharpness.floatValue,
                               GvrAudio.sourceDirectivityColor,
                               (int)(3.0f * EditorGUIUtility.singleLineHeight));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.PropertyField(occlusionEnabled, occlusionLabel);

        EditorGUILayout.Separator();

        // HRTF toggle can only be modified through the Inspector in Edit mode.
        EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying);
        EditorGUILayout.PropertyField(hrtfEnabled, hrtfEnabledLabel);
        EditorGUI.EndDisabledGroup();

        serializedObject.ApplyModifiedProperties();
    }
Пример #9
0
        protected void InspectorGUI()
        {
            #region Simple
            {
                EditorGUI.BeginChangeCheck();
                var mode = GUILayout.Toolbar(objectTarget.advancedMode ? 1 : 0, VoxelBaseEditor.Edit_AdvancedModeStrings);
                if (EditorGUI.EndChangeCheck())
                {
                    objectTarget.advancedMode = mode != 0 ? true : false;
                }
            }
            #endregion

            EditorGUILayout.Space();

            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.Space();
                if (GUILayout.Button("Reset Transform"))
                {
                    Undo.RecordObject(chunkTarget.transform, "Reset Chunk Transform");
                    chunkTarget.transform.localPosition = chunkTarget.basicOffset;
                    chunkTarget.transform.localRotation = Quaternion.identity;
                    chunkTarget.transform.localScale    = Vector3.one;
                }
                EditorGUILayout.Space();
                EditorGUILayout.EndHorizontal();
            }

            #region Object
            if (objectTarget.advancedMode)
            {
                chunkTarget.edit_objectFoldout = EditorGUILayout.Foldout(chunkTarget.edit_objectFoldout, "Object", guiStyleFoldoutBold);
                if (chunkTarget.edit_objectFoldout)
                {
                    EditorGUILayout.BeginVertical(GUI.skin.box);
                    #region Mesh
                    {
                        EditorGUILayout.LabelField("Mesh", EditorStyles.boldLabel);
                        EditorGUI.indentLevel++;
                        #region Mesh
                        {
                            EditorGUILayout.BeginHorizontal();
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.ObjectField(chunkTarget.mesh, typeof(Mesh), false);
                                EditorGUI.EndDisabledGroup();
                            }
                            if (chunkTarget.mesh != null)
                            {
                                if (!EditorCommon.IsMainAsset(chunkTarget.mesh))
                                {
                                    if (GUILayout.Button("Save", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Create Mesh
                                        string path = EditorUtility.SaveFilePanel("Save mesh", chunkCore.GetDefaultPath(), string.Format("{0}_{1}_mesh.asset", objectTarget.gameObject.name, chunkTarget.chunkName), "asset");
                                        if (!string.IsNullOrEmpty(path))
                                        {
                                            if (path.IndexOf(Application.dataPath) < 0)
                                            {
                                                EditorCommon.SaveInsideAssetsFolderDisplayDialog();
                                            }
                                            else
                                            {
                                                Undo.RecordObject(objectTarget, "Save Mesh");
                                                Undo.RecordObject(chunkTarget, "Save Mesh");
                                                path = FileUtil.GetProjectRelativePath(path);
                                                AssetDatabase.CreateAsset(Mesh.Instantiate(chunkTarget.mesh), path);
                                                chunkTarget.mesh = AssetDatabase.LoadAssetAtPath <Mesh>(path);
                                                Refresh();
                                            }
                                        }
                                        #endregion
                                    }
                                }
                                {
                                    if (GUILayout.Button("Reset", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Reset Mesh
                                        Undo.RecordObject(objectTarget, "Reset Mesh");
                                        Undo.RecordObject(chunkTarget, "Reset Mesh");
                                        chunkTarget.mesh = null;
                                        Refresh();
                                        #endregion
                                    }
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        #endregion
                        #region Vertex Count
                        {
                            EditorGUILayout.LabelField("Vertex Count", chunkTarget.mesh != null ? chunkTarget.mesh.vertexCount.ToString() : "");
                        }
                        #endregion
                        EditorGUI.indentLevel--;
                    }
                    #endregion
                    #region Material
                    if (objectTarget.materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        EditorGUILayout.LabelField("Material", EditorStyles.boldLabel);
                        EditorGUI.indentLevel++;
                        #region Material
                        for (int i = 0; i < chunkTarget.materials.Count; i++)
                        {
                            EditorGUILayout.BeginHorizontal();
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.ObjectField(chunkTarget.materials[i], typeof(Material), false);
                                EditorGUI.EndDisabledGroup();
                            }
                            if (chunkTarget.materials[i] != null)
                            {
                                if (!EditorCommon.IsMainAsset(chunkTarget.materials[i]))
                                {
                                    if (GUILayout.Button("Save", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Create Material
                                        string defaultName = string.Format("{0}_{1}_mat{2}.mat", objectTarget.gameObject.name, chunkTarget.chunkName, i);
                                        string path        = EditorUtility.SaveFilePanel("Save material", chunkCore.GetDefaultPath(), defaultName, "mat");
                                        if (!string.IsNullOrEmpty(path))
                                        {
                                            if (path.IndexOf(Application.dataPath) < 0)
                                            {
                                                EditorCommon.SaveInsideAssetsFolderDisplayDialog();
                                            }
                                            else
                                            {
                                                Undo.RecordObject(objectTarget, "Save Material");
                                                Undo.RecordObject(chunkTarget, "Save Material");
                                                path = FileUtil.GetProjectRelativePath(path);
                                                AssetDatabase.CreateAsset(Material.Instantiate(chunkTarget.materials[i]), path);
                                                chunkTarget.materials[i] = AssetDatabase.LoadAssetAtPath <Material>(path);
                                                Refresh();
                                            }
                                        }

                                        #endregion
                                    }
                                }
                                {
                                    if (GUILayout.Button("Reset", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Reset Material
                                        Undo.RecordObject(objectTarget, "Reset Material");
                                        Undo.RecordObject(chunkTarget, "Reset Material");
                                        chunkTarget.materials[i] = EditorCommon.Instantiate(chunkTarget.materials[i]);
                                        Refresh();
                                        #endregion
                                    }
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        #endregion
                        EditorGUI.indentLevel--;
                    }
                    #endregion
                    #region Texture
                    if (objectTarget.materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        EditorGUILayout.LabelField("Texture", EditorStyles.boldLabel);
                        EditorGUI.indentLevel++;
                        #region Texture
                        {
                            EditorGUILayout.BeginHorizontal();
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.ObjectField(chunkTarget.atlasTexture, typeof(Texture2D), false);
                                EditorGUI.EndDisabledGroup();
                            }
                            if (chunkTarget.atlasTexture != null)
                            {
                                if (!EditorCommon.IsMainAsset(chunkTarget.atlasTexture))
                                {
                                    if (GUILayout.Button("Save", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Create Texture
                                        string defaultName = string.Format("{0}_{1}_tex.png", objectTarget.gameObject.name, chunkTarget.chunkName);
                                        string path        = EditorUtility.SaveFilePanel("Save atlas texture", chunkCore.GetDefaultPath(), defaultName, "png");
                                        if (!string.IsNullOrEmpty(path))
                                        {
                                            if (path.IndexOf(Application.dataPath) < 0)
                                            {
                                                EditorCommon.SaveInsideAssetsFolderDisplayDialog();
                                            }
                                            else
                                            {
                                                Undo.RecordObject(objectTarget, "Save Atlas Texture");
                                                Undo.RecordObject(chunkTarget, "Save Atlas Texture");
                                                File.WriteAllBytes(path, chunkTarget.atlasTexture.EncodeToPNG());
                                                path = FileUtil.GetProjectRelativePath(path);
                                                AssetDatabase.ImportAsset(path);
                                                objectCore.SetTextureImporterSetting(path, chunkTarget.atlasTexture);
                                                chunkTarget.atlasTexture = AssetDatabase.LoadAssetAtPath <Texture2D>(path);
                                                Refresh();
                                            }
                                        }
                                        #endregion
                                    }
                                }
                                {
                                    if (GUILayout.Button("Reset", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Reset Texture
                                        Undo.RecordObject(objectTarget, "Reset Atlas Texture");
                                        Undo.RecordObject(chunkTarget, "Reset Atlas Texture");
                                        chunkTarget.atlasTexture = null;
                                        Refresh();
                                        #endregion
                                    }
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        #endregion
                        #region Texture Size
                        {
                            EditorGUILayout.LabelField("Texture Size", chunkTarget.atlasTexture != null ? string.Format("{0} x {1}", chunkTarget.atlasTexture.width, chunkTarget.atlasTexture.height) : "");
                        }
                        #endregion
                        EditorGUI.indentLevel--;
                    }
                    #endregion
                    EditorGUILayout.EndVertical();
                }
            }
            else
            {
                EditorGUILayout.Space();
            }
            #endregion

            #region Refresh
            if (GUILayout.Button("Refresh"))
            {
                Undo.RecordObject(objectTarget, "Inspector");
                Undo.RecordObject(chunkTarget, "Inspector");
                Refresh();
            }
            #endregion
        }
        protected override void CreateGUI()
        {
            // Collect all Triggers that target this Objective Action.
            List <Trigger> targetingTriggers = m_ObjectiveAction.GetTargetingTriggers();

            // Check if trigger is already registered with the Objective Action.
            foreach (var targetingTrigger in targetingTriggers)
            {
                var foundTrigger = false;
                for (var i = 0; i < m_TriggersProp.arraySize; ++i)
                {
                    if (m_TriggersProp.GetArrayElementAtIndex(i).objectReferenceValue == targetingTrigger)
                    {
                        foundTrigger = true;
                        break;
                    }
                }

                // If trigger was new, set up the corresponding objective with reasonable default values.
                if (!foundTrigger)
                {
                    m_TriggersProp.arraySize++;
                    m_ObjectiveConfigurationsProp.arraySize++;
                    m_TriggersProp.GetArrayElementAtIndex(m_TriggersProp.arraySize - 1).objectReferenceValue = targetingTrigger;

                    var objectiveConfigurationProp = m_ObjectiveConfigurationsProp.GetArrayElementAtIndex(m_ObjectiveConfigurationsProp.arraySize - 1);
                    var objectiveConfiguration     = m_ObjectiveAction.GetDefaultObjectiveConfiguration(targetingTrigger);
                    objectiveConfigurationProp.FindPropertyRelative("Title").stringValue           = objectiveConfiguration.Title;
                    objectiveConfigurationProp.FindPropertyRelative("Description").stringValue     = objectiveConfiguration.Description;
                    objectiveConfigurationProp.FindPropertyRelative("ProgressType").enumValueIndex = (int)objectiveConfiguration.ProgressType;
                    objectiveConfigurationProp.FindPropertyRelative("Lose").boolValue   = objectiveConfiguration.Lose;
                    objectiveConfigurationProp.FindPropertyRelative("Hidden").boolValue = objectiveConfiguration.Hidden;
                }
            }

            EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying);

            // Show the objectives of the currently targeting triggers.
            for (var i = 0; i < m_TriggersProp.arraySize; ++i)
            {
                var trigger = (Trigger)m_TriggersProp.GetArrayElementAtIndex(i).objectReferenceValue;

                if (targetingTriggers.Contains(trigger))
                {
                    var label = trigger.GetType().ToString();
                    label = label.Substring(label.LastIndexOf('.') + 1);
                    label = ObjectNames.NicifyVariableName(label);
                    var objectiveConfigurationProp = m_ObjectiveConfigurationsProp.GetArrayElementAtIndex(i);
                    GUI.SetNextControlName("Trigger " + i);
                    if (EditorGUILayout.PropertyField(objectiveConfigurationProp, new GUIContent("Objective for " + label), false))
                    {
                        EditorGUI.indentLevel++;
                        GUI.SetNextControlName("Trigger Title " + i);
                        EditorGUILayout.PropertyField(objectiveConfigurationProp.FindPropertyRelative("Title"), new GUIContent("Title", "The title of the objective."));
                        GUI.SetNextControlName("Trigger Description " + i);
                        EditorGUILayout.PropertyField(objectiveConfigurationProp.FindPropertyRelative("Description"), new GUIContent("Details", "The details of the objective."));
                        GUI.SetNextControlName("Trigger Hidden " + i);
                        EditorGUILayout.PropertyField(objectiveConfigurationProp.FindPropertyRelative("Hidden"), new GUIContent("Hidden", "Hide the objective from the player."));
                        EditorGUI.indentLevel--;
                    }
                }
            }

            EditorGUI.EndDisabledGroup();

            var previousFocusedTrigger = m_FocusedTrigger;

            // Find the currently focused Trigger.
            var focusedControlName = GUI.GetNameOfFocusedControl();
            var lastSpace          = focusedControlName.LastIndexOf(' ');

            if (focusedControlName.StartsWith("Trigger") && lastSpace >= 0)
            {
                var index = int.Parse(focusedControlName.Substring(lastSpace + 1));
                m_FocusedTrigger = (Trigger)m_TriggersProp.GetArrayElementAtIndex(index).objectReferenceValue;
            }
            else
            {
                m_FocusedTrigger = null;
            }

            if (m_FocusedTrigger != previousFocusedTrigger)
            {
                SceneView.RepaintAll();
            }
        }
        protected virtual void ShowMainGUI(MaterialEditor matEditor)
        {
            ShowBlendModeGUI(matEditor);

            var mode = (BlendMode)blendMode.floatValue;
            var mat  = matEditor.target as Material;

            ShaderGUIUtils.BeginHeader("Base Texture and Color");
            {
                matEditor.ShaderProperty(vertexColorEnabled, Styles.vertexColorEnabled);

                CustomMaterialEditor.TextureWithToggleableColorAutoScaleOffsetSingleLine(matEditor, Styles.main,
                                                                                         mainTexture,
                                                                                         mainColorEnabled, mainColor,
                                                                                         textureScaleAndOffset);

                matEditor.TexturePropertySingleLine(Styles.occlusionMap, occlusionMap);

                if (mode == BlendMode.Cutout)
                {
                    matEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text);
                }
            }
            ShaderGUIUtils.EndHeader();
            ShaderGUIUtils.HeaderSeparator();

            ShaderGUIUtils.BeginHeader("Lighting");
            {
                matEditor.ShaderProperty(ambientLightingEnabled, Styles.ambientLightingEnabled);
                matEditor.ShaderProperty(diffuseLightingEnabled, Styles.diffuseLightingEnabled);
                matEditor.ShaderProperty(useAdditionalLightingData, Styles.useAdditionalLighingData);
                EditorGUI.BeginDisabledGroup(MaterialNeedsPerPixel(mat));
                matEditor.ShaderProperty(perPixelLighting, Styles.perPixelLighting);
                EditorGUI.EndDisabledGroup();

                ShaderGUIUtils.BeginHeaderProperty(matEditor, Styles.specularLightingEnabled.text, specularLightingEnabled);
                {
                    if (specularLightingEnabled.floatValue != 0.0f)
                    {
                        matEditor.ShaderProperty(specularColor, Styles.specularColor);

                        //consider a special slider + tex control
                        matEditor.TexturePropertySingleLine(Styles.specular, specularMap, specular);
                        matEditor.TexturePropertySingleLine(Styles.gloss, glossMap, gloss);
                    }
                }
                ShaderGUIUtils.EndHeader();

                matEditor.TexturePropertySingleLine(Styles.normalMap, normalMap);

                ShaderGUIUtils.BeginHeaderProperty(matEditor, Styles.rimLightingEnabled.text, rimLightingEnabled);
                {
                    if (rimLightingEnabled.floatValue != 0.0f)
                    {
                        matEditor.ShaderProperty(rimPower, Styles.rimPower);
                        matEditor.ShaderProperty(rimColor, Styles.rimColor);
                    }
                }
                ShaderGUIUtils.EndHeader();

                ShaderGUIUtils.BeginHeaderProperty(matEditor, Styles.reflectionsEnabled.text, reflectionsEnabled);
                {
                    if (reflectionsEnabled.floatValue != 0.0f)
                    {
                        matEditor.TexturePropertySingleLine(Styles.cubeMap, cubeMap);
                        matEditor.ShaderProperty(reflectionScale, Styles.reflectionScale);
                        matEditor.ShaderProperty(calibrationSpaceReflections, Styles.calibrationSpaceReflections);
                    }
                }
                ShaderGUIUtils.EndHeader();

                CustomMaterialEditor.TextureWithToggleableColorSingleLine(matEditor, Styles.emission, emissionMap, emissionColorEnabled, emissionColor);
            }
            ShaderGUIUtils.EndHeader();
            ShaderGUIUtils.HeaderSeparator();

            ShaderGUIUtils.BeginHeader("Global");
            {
                CustomMaterialEditor.TextureScaleOffsetVector4Property(matEditor, Styles.textureScaleAndOffset, textureScaleAndOffset);
            }
            ShaderGUIUtils.EndHeader();
            ShaderGUIUtils.HeaderSeparator();

            if (mode == BlendMode.Advanced)
            {
                ShaderGUIUtils.BeginHeader("Alpha Blending");
                {
                    matEditor.ShaderProperty(srcBlend, Styles.srcBlend);
                    matEditor.ShaderProperty(dstBlend, Styles.dstBlend);
                    matEditor.ShaderProperty(blendOp, Styles.blendOp);
                }
                ShaderGUIUtils.EndHeader();
                ShaderGUIUtils.HeaderSeparator();
            }
        }
Пример #12
0
        private void DrawSubmitButtonSingle(BKI_Hand hand, float buttonWidth)
        {
            bool rh   = (rhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME && hand == BKI_Hand.right);
            bool lh   = (lhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME && hand == BKI_Hand.left);
            bool both = (rhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME && hand == BKI_Hand.right) || (lhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME && hand == BKI_Hand.left);

            string defaultString  = "Save current gesture";
            string tooltipWarning = "";

            if (hand == BKI_Hand.right)
            {
                DrawOpenGestureButton(BKI_UIType.right, buttonWidth);

                if ((rhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME))
                {
                    tooltipWarning = "Gesture name can't be [" + DEFAULT_GESTURE_NAME + "].";
                }
                else if (rhGesture.gestureIdentifier.Length < 1)
                {
                    tooltipWarning = "Gesture name can't be empty.";
                }
                else if (!isOpenedFromResourcesRh && gestureStorage.EntryAlreadyExists(BKI_Hand.right, rhGesture))
                {
                    tooltipWarning = "This gesture name is already used.";
                }
                else
                {
                    tooltipWarning = defaultString;
                }

                EditorGUI.BeginDisabledGroup(tooltipWarning != defaultString);
                {
                    if (GUILayout.Button(new GUIContent("Save right hand \n gesture", tooltipWarning), GUILayout.Height(buttonHeight), GUILayout.Width(buttonWidth)))
                    {
                        Debug.Log("Save rh \n gesture");
                        SubmitSingleHandGesture(BKI_Hand.right, rhGesture, isOpenedFromResourcesRh);
                        currentGestureSavedRh   = true;
                        pickerWindowGNameRh     = rhGesture.gestureIdentifier;
                        isOpenedFromResourcesRh = true;
                    }
                }
                EditorGUI.EndDisabledGroup();
            }
            else
            {
                DrawOpenGestureButton(BKI_UIType.left, buttonWidth);

                if ((lhGesture.gestureIdentifier == DEFAULT_GESTURE_NAME))
                {
                    tooltipWarning = "Gesture name can't be [" + DEFAULT_GESTURE_NAME + "].";
                }
                else if (lhGesture.gestureIdentifier.Length < 1)
                {
                    tooltipWarning = "Gesture name can't be empty.";
                }
                else if (!isOpenedFromResourcesLh && gestureStorage.EntryAlreadyExists(BKI_Hand.left, lhGesture))
                {
                    tooltipWarning = "This gesture name is already used.";
                }
                else
                {
                    tooltipWarning = defaultString;
                }

                EditorGUI.BeginDisabledGroup(tooltipWarning != defaultString);
                {
                    if (GUILayout.Button(new GUIContent("Save left hand \n gesture", tooltipWarning), GUILayout.Height(buttonHeight), GUILayout.Width(buttonWidth)))
                    {
                        Debug.Log("Save lh \n gesture");
                        SubmitSingleHandGesture(BKI_Hand.left, lhGesture, isOpenedFromResourcesLh);
                        currentGestureSavedLh   = true;
                        pickerWindowGNameLh     = lhGesture.gestureIdentifier;
                        isOpenedFromResourcesLh = true;
                    }
                }
                EditorGUI.EndDisabledGroup();
            }
        }
Пример #13
0
            public override void OnInspectorGUI()
            {
                var insp = ((ChangerPlateInspector)target).changerPlate;

                var changerId = insp.changerId;

                GUILayout.Label("changerId:" + changerId);

                var changerName = insp.changerName;

                using (new GUILayout.HorizontalScope())
                {
                    GUILayout.Label("Changer Name", GUILayout.Width(100));
                    var result = GUILayout.TextField(changerName);
                    if (result != changerName)
                    {
                        insp.UpdateChangerName(result);
                    }
                }

                var changerComments = string.Join("\n", insp.comments.ToArray());

                using (new GUILayout.HorizontalScope())
                {
                    GUILayout.Label("Comment", GUILayout.Width(100));
                    var result = GUILayout.TextArea(changerComments);
                    if (result != changerComments)
                    {
                        insp.UpdateChangerComment(result);
                    }
                }

                GUILayout.Space(10);

                // branch.
                using (new GUILayout.VerticalScope(GUI.skin.box, new GUILayoutOption[0]))
                {
                    GUILayout.Label("Branch");
                    if (insp.branchBinds.Any())
                    {
                        var binds = insp.branchBinds;
                        foreach (var bind in binds.Select((val, index) => new { val, index }))
                        {
                            using (new GUILayout.HorizontalScope(GUI.skin.box, new GUILayoutOption[0]))
                            {
                                if (GUILayout.Button(string.Empty, "OL Minus", GUILayout.Width(20)))
                                {
                                    insp.DeleteBind(bind.index);
                                }
                                using (new GUILayout.VerticalScope())
                                {
                                    var kind = bind.val.bindKind;
                                    if (GUILayout.Button(kind, "LargePopup"))
                                    {
                                        ShowContextMenuOfBind(insp, bind.val);
                                    }
                                    using (new GUILayout.VerticalScope(GUI.skin.box, new GUILayoutOption[0]))
                                    {
                                        // combinations
                                        foreach (var combination in bind.val.combinations.Select((val, index) => new { val, index }))
                                        {
                                            using (new GUILayout.HorizontalScope())
                                            {
                                                if (GUILayout.Button(string.Empty, "OL Minus", GUILayout.Width(20)))
                                                {
                                                    insp.DeleteBranchConditionAt(bind.index, combination.index);
                                                }

                                                if (GUILayout.Button(combination.val.conditionType, "GV Gizmo DropDown"))
                                                {
                                                    ShowContextMenuOfType(insp, combination.val);
                                                }

                                                if (GUILayout.Button(combination.val.conditionValue, "GV Gizmo DropDown"))
                                                {
                                                    ShowContextMenuOfValue(insp, combination.val);
                                                }
                                            }
                                            GUILayout.Space(5);
                                        }

                                        // combination + button.
                                        if (GUILayout.Button(string.Empty, "OL Plus", GUILayout.Width(20)))
                                        {
                                            insp.AddCombinationToBind(bind.index);
                                        }
                                    }
                                }
                            }
                        }

                        using (new GUILayout.HorizontalScope())
                        {
                            GUILayout.FlexibleSpace();

                            // bind + button.
                            if (GUILayout.Button("+ Add Condition", GUILayout.Width(120)))
                            {
                                insp.AddBind(ChangerCondKey.CONTAINS);
                            }
                        }

                        GUILayout.Space(10);

                        var useContinue = GUILayout.Toggle(insp.useContinue, "Continue Current Auto");
                        if (useContinue != insp.useContinue)
                        {
                            insp.UpdateUseContinue(useContinue);
                        }

                        GUILayout.Space(5);

                        EditorGUI.BeginDisabledGroup(insp.useContinue);
                        {
                            // branch next auto.
                            using (new GUILayout.HorizontalScope())
                            {
                                GUILayout.Label("Next Auto");
                                if (GUILayout.Button(insp.AutoNameFromId(insp.branchAutoId), "LargePopup"))
                                {
                                    Debug.LogError("このAuto以外のNameを出すコンテキストメニュー");
                                }
                            }

                            // branch inherits.
                            using (new GUILayout.HorizontalScope())
                            {
                                GUILayout.Label("Inherit Timeline Type");
                                GUILayout.FlexibleSpace();
                                using (new GUILayout.VerticalScope(GUI.skin.box, GUILayout.Width(130)))
                                {
                                    foreach (var inheritType in insp.branchInheritTypes.Select((val, index) => new { index, val }))
                                    {
                                        using (new GUILayout.HorizontalScope())
                                        {
                                            if (GUILayout.Button(string.Empty, "OL Minus", GUILayout.Width(20)))
                                            {
                                                insp.DeleteBranchInheritAt(inheritType.index);
                                            }
                                            if (GUILayout.Button(inheritType.val, "GV Gizmo DropDown"))
                                            {
                                                Debug.LogError("Typeを選ぶコンテキストメニューだす");
                                            }
                                        }
                                        GUILayout.Space(5);
                                    }
                                    if (GUILayout.Button(string.Empty, "OL Plus", GUILayout.Width(20)))
                                    {
                                        insp.AddBranchInheritCondition();
                                    }
                                }
                            }
                        }
                        EditorGUI.EndDisabledGroup();
                    }
                    else
                    {
                        // bind + button.
                        if (GUILayout.Button("+ Add Condition", GUILayout.Width(120)))
                        {
                            insp.AddBind(ChangerCondKey.CONTAINS);
                        }
                    }
                }

                GUILayout.Space(10);

                // finally.
                using (new GUILayout.VerticalScope(GUI.skin.box, new GUILayoutOption[0]))
                {
                    GUILayout.Label("Finally");

                    var showFinally = GUILayout.Toggle(insp.useFinally, "Use Finally");
                    if (showFinally != insp.useFinally)
                    {
                        insp.UpdateUseFinally(showFinally);
                    }
                    if (showFinally)
                    {
                        GUILayout.Space(10);

                        // finally next auto.
                        using (new GUILayout.HorizontalScope())
                        {
                            GUILayout.Label("Next Auto");
                            if (GUILayout.Button(insp.AutoNameFromId(insp.finallyAutoId), "LargePopup"))
                            {
                                Debug.LogError("このAuto以外のNameを出すコンテキストメニュー");
                            }
                        }

                        // finally inherits.
                        using (new GUILayout.HorizontalScope())
                        {
                            GUILayout.Label("Inherit Timeline Type");
                            GUILayout.FlexibleSpace();
                            using (new GUILayout.VerticalScope(GUI.skin.box, GUILayout.Width(130)))
                            {
                                foreach (var inheritType in insp.finallyInheritTypes.Select((val, index) => new { index, val }))
                                {
                                    using (new GUILayout.HorizontalScope())
                                    {
                                        if (GUILayout.Button(string.Empty, "OL Minus", GUILayout.Width(20)))
                                        {
                                            insp.DeleteFinallyInheritAt(inheritType.index);
                                        }
                                        if (GUILayout.Button(inheritType.val, "GV Gizmo DropDown"))
                                        {
                                            Debug.LogError("Typeを選ぶコンテキストメニューだす");
                                        }
                                    }
                                    GUILayout.Space(5);
                                }
                                if (GUILayout.Button(string.Empty, "OL Plus", GUILayout.Width(20)))
                                {
                                    insp.AddFinallyInheritCondition();
                                }
                            }
                        }
                    }
                }
            }
Пример #14
0
        public override void OnInspectorGUI()
        {
            CUIGraphic script = (CUIGraphic)this.target;

            EditorGUILayout.HelpBox("CurlyUI (CUI) should work with most of the Unity UI. For Image, use CUIImage; for Text, use CUIText; and for others (e.g. RawImage), use CUIGraphic", MessageType.Info);

            if (script.UIGraphic == null)
            {
                EditorGUILayout.HelpBox("CUI is an extension to Unity's UI. You must set Ui Graphic with a Unity Graphic component (e.g. Image, Text, RawImage)", MessageType.Error);
            }
            else
            {
                if (script.UIGraphic is Image && script.GetType() != typeof(CUIImage))
                {
                    EditorGUILayout.HelpBox("Although CUI components are generalized. It is recommended that for Image, use CUIImage", MessageType.Warning);
                }
                else if (script.UIGraphic is Text && script.GetType() != typeof(CUIText))
                {
                    EditorGUILayout.HelpBox("Although CUI components are generalized. It is recommended that for Text, use CUIText", MessageType.Warning);
                }

                EditorGUILayout.HelpBox("Now that CUI is ready, change the control points of the top and bottom bezier curves to curve/morph the UI. Improve resolution when the UI seems to look poorly when curved/morphed should help.", MessageType.Info);
            }

            DrawDefaultInspector();

            // draw the editor that shows the position ratio of all control points from the two bezier curves
            isCurveGpFold = EditorGUILayout.Foldout(isCurveGpFold, "Curves Position Ratios");
            if (isCurveGpFold)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.LabelField("Top Curve");
                EditorGUI.indentLevel++;
                Vector3[] controlPoints = script.RefCurvesControlRatioPoints[1].array;

                EditorGUI.BeginChangeCheck();
                for (int p = 0; p < controlPoints.Length; p++)
                {
                    reuse_Vector3s[p] = EditorGUILayout.Vector3Field(string.Format("Control Points {0}", p + 1), controlPoints[p]);
                }

                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(script, "Change Ratio Points");
                    EditorUtility.SetDirty(script);

                    System.Array.Copy(reuse_Vector3s, script.RefCurvesControlRatioPoints[1].array, controlPoints.Length);
                    script.UpdateCurveControlPointPositions();
                }
                EditorGUI.indentLevel--;
                EditorGUILayout.LabelField("Bottom Curve");
                EditorGUI.indentLevel++;
                controlPoints = script.RefCurvesControlRatioPoints[0].array;

                EditorGUI.BeginChangeCheck();
                for (int p = 0; p < controlPoints.Length; p++)
                {
                    reuse_Vector3s[p] = EditorGUILayout.Vector3Field(string.Format("Control Points {0}", p + 1), controlPoints[p]);
                }

                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(script, "Change Ratio Points");
                    EditorUtility.SetDirty(script);

                    System.Array.Copy(reuse_Vector3s, controlPoints, controlPoints.Length);
                    script.UpdateCurveControlPointPositions();
                }
                EditorGUI.indentLevel--;
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("Fit Bezier curves to rect transform"))
            {
                Undo.RecordObject(script, "Fit to Rect Transform");
                Undo.RecordObject(script.RefCurves[0], "Fit to Rect Transform");
                Undo.RecordObject(script.RefCurves[1], "Fit to Rect Transform");
                EditorUtility.SetDirty(script);

                script.FixTextToRectTrans();

                script.Refresh();
            }

            EditorGUILayout.Space();

            // disable group to prevent allowing the reference be used when there is no reference CUI
            EditorGUI.BeginDisabledGroup(script.RefCUIGraphic == null);

            if (GUILayout.Button("Reference CUI component for curves"))
            {
                Undo.RecordObject(script, "Reference Reference CUI");
                Undo.RecordObject(script.RefCurves[0], "Reference Reference CUI");
                Undo.RecordObject(script.RefCurves[1], "Reference Reference CUI");
                EditorUtility.SetDirty(script);

                script.ReferenceCUIForBCurves();

                script.Refresh();
            }

            EditorGUILayout.HelpBox("Auto set the curves' control points by refencing another CUI. You need to set Ref CUI Graphic (e.g. CUIImage) first.", MessageType.Info);

            EditorGUI.EndDisabledGroup();
        }
Пример #15
0
        private void DoActionbarGUI()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            {
                if (hasRemote)
                {
                    EditorGUI.BeginDisabledGroup(currentRemoteName == null);
                    {
                        // Fetch button
                        var fetchClicked = GUILayout.Button(fetchButtonContent, Styles.ToolbarButtonStyle);
                        if (fetchClicked)
                        {
                            Fetch();
                        }

                        // Pull button
                        var pullButtonText = statusBehind > 0 ? new GUIContent(String.Format(Localization.PullButtonCount, statusBehind)) : pullButtonContent;
                        var pullClicked = GUILayout.Button(pullButtonText, Styles.ToolbarButtonStyle);

                        if (pullClicked &&
                            EditorUtility.DisplayDialog(Localization.PullConfirmTitle,
                                String.Format(Localization.PullConfirmDescription, currentRemoteName),
                                Localization.PullConfirmYes,
                                Localization.Cancel)
                        )
                        {
                            Pull();
                        }
                    }
                    EditorGUI.EndDisabledGroup();

                    // Push button
                    EditorGUI.BeginDisabledGroup(currentRemoteName == null || isTrackingRemoteBranch && statusAhead == 0);
                    {
                        var pushButtonText = statusAhead > 0 ? new GUIContent(String.Format(Localization.PushButtonCount, statusAhead)) : pushButtonContent;
                        var pushClicked = GUILayout.Button(pushButtonText, Styles.ToolbarButtonStyle);

                        if (pushClicked &&
                            EditorUtility.DisplayDialog(Localization.PushConfirmTitle,
                                String.Format(Localization.PushConfirmDescription, currentRemoteName),
                                Localization.PushConfirmYes,
                                Localization.Cancel)
                        )
                        {
                            Push();
                        }
                    }
                    EditorGUI.EndDisabledGroup();
                }
                else
                {
                    // Publishing a repo
                    if (GUILayout.Button(Localization.PublishButton, Styles.ToolbarButtonStyle))
                    {
                        PopupWindow.OpenWindow(PopupWindow.PopupViewType.PublishView);
                    }
                }

                if (GUILayout.Button(refreshButtonContent, Styles.ToolbarButtonStyle))
                {
                    Refresh();
                }

                GUILayout.FlexibleSpace();

                if (!connections.Any())
                {
                    if (GUILayout.Button("Sign in", EditorStyles.toolbarButton))
                        SignIn(null);
                }
                else
                {
                    var connection = connections.First();
                    if (GUILayout.Button(connection.Username, EditorStyles.toolbarDropDown))
                    {
                        DoAccountDropdown();
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
        }
Пример #16
0
        /// <summary>Draws the inspector for a \link Pathfinding.GraphCollision GraphCollision class \endlink</summary>
        protected virtual void DrawCollisionEditor(GraphCollision collision)
        {
            collision = collision ?? new GraphCollision();

            DrawUse2DPhysics(collision);

            collision.collisionCheck = ToggleGroup("Collision testing", collision.collisionCheck);
            if (collision.collisionCheck)
            {
                string[] colliderOptions = collision.use2D ? new [] { "Circle", "Point" } : new [] { "Sphere", "Capsule", "Ray" };
                int[]    colliderValues  = collision.use2D ? new [] { 0, 2 } : new [] { 0, 1, 2 };
                // In 2D the Circle (Sphere) mode will replace both the Sphere and the Capsule modes
                // However make sure that the original value is still stored in the grid graph in case the user changes back to the 3D mode in the inspector.
                var tp = collision.type;
                if (tp == ColliderType.Capsule && collision.use2D)
                {
                    tp = ColliderType.Sphere;
                }
                EditorGUI.BeginChangeCheck();
                tp = (ColliderType)EditorGUILayout.IntPopup("Collider type", (int)tp, colliderOptions, colliderValues);
                if (EditorGUI.EndChangeCheck())
                {
                    collision.type = tp;
                }

                // Only spheres and capsules have a diameter
                if (collision.type == ColliderType.Capsule || collision.type == ColliderType.Sphere)
                {
                    collision.diameter = EditorGUILayout.FloatField(new GUIContent("Diameter", "Diameter of the capsule or sphere. 1 equals one node width"), collision.diameter);
                }

                if (!collision.use2D)
                {
                    if (collision.type == ColliderType.Capsule || collision.type == ColliderType.Ray)
                    {
                        collision.height = EditorGUILayout.FloatField(new GUIContent("Height/Length", "Height of cylinder or length of ray in world units"), collision.height);
                    }

                    collision.collisionOffset = EditorGUILayout.FloatField(new GUIContent("Offset", "Offset upwards from the node. Can be used so that obstacles can be used as ground and at the same time as obstacles for lower positioned nodes"), collision.collisionOffset);
                }

                collision.mask = EditorGUILayoutx.LayerMaskField("Obstacle Layer Mask", collision.mask);

                DrawCollisionPreview(collision);
            }

            GUILayout.Space(2);

            if (collision.use2D)
            {
                EditorGUI.BeginDisabledGroup(collision.use2D);
                ToggleGroup("Height testing", false);
                EditorGUI.EndDisabledGroup();
            }
            else
            {
                collision.heightCheck = ToggleGroup("Height testing", collision.heightCheck);
                if (collision.heightCheck)
                {
                    collision.fromHeight = EditorGUILayout.FloatField(new GUIContent("Ray length", "The height from which to check for ground"), collision.fromHeight);

                    collision.heightMask = EditorGUILayoutx.LayerMaskField("Mask", collision.heightMask);

                    collision.thickRaycast = EditorGUILayout.Toggle(new GUIContent("Thick Raycast", "Use a thick line instead of a thin line"), collision.thickRaycast);

                    if (collision.thickRaycast)
                    {
                        EditorGUI.indentLevel++;
                        collision.thickRaycastDiameter = EditorGUILayout.FloatField(new GUIContent("Diameter", "Diameter of the thick raycast"), collision.thickRaycastDiameter);
                        EditorGUI.indentLevel--;
                    }

                    collision.unwalkableWhenNoGround = EditorGUILayout.Toggle(new GUIContent("Unwalkable when no ground", "Make nodes unwalkable when no ground was found with the height raycast. If height raycast is turned off, this doesn't affect anything"), collision.unwalkableWhenNoGround);
                }
            }
        }
Пример #17
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            serializedObject.Update();

            UIComponent t = (UIComponent)target;

            EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
            {
                EditorGUILayout.PropertyField(m_EnableOpenUIFormSuccessEvent);
                EditorGUILayout.PropertyField(m_EnableOpenUIFormFailureEvent);
                EditorGUILayout.PropertyField(m_EnableOpenUIFormUpdateEvent);
                EditorGUILayout.PropertyField(m_EnableOpenUIFormDependencyAssetEvent);
                EditorGUILayout.PropertyField(m_EnableCloseUIFormCompleteEvent);
            }
            EditorGUI.EndDisabledGroup();

            float instanceAutoReleaseInterval = EditorGUILayout.DelayedFloatField("Instance Auto Release Interval", m_InstanceAutoReleaseInterval.floatValue);

            if (instanceAutoReleaseInterval != m_InstanceAutoReleaseInterval.floatValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.InstanceAutoReleaseInterval = instanceAutoReleaseInterval;
                }
                else
                {
                    m_InstanceAutoReleaseInterval.floatValue = instanceAutoReleaseInterval;
                }
            }

            int instanceCapacity = EditorGUILayout.DelayedIntField("Instance Capacity", m_InstanceCapacity.intValue);

            if (instanceCapacity != m_InstanceCapacity.intValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.InstanceCapacity = instanceCapacity;
                }
                else
                {
                    m_InstanceCapacity.intValue = instanceCapacity;
                }
            }

            float instanceExpireTime = EditorGUILayout.DelayedFloatField("Instance Expire Time", m_InstanceExpireTime.floatValue);

            if (instanceExpireTime != m_InstanceExpireTime.floatValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.InstanceExpireTime = instanceExpireTime;
                }
                else
                {
                    m_InstanceExpireTime.floatValue = instanceExpireTime;
                }
            }

            int instancePriority = EditorGUILayout.DelayedIntField("Instance Priority", m_InstancePriority.intValue);

            if (instancePriority != m_InstancePriority.intValue)
            {
                if (EditorApplication.isPlaying)
                {
                    t.InstancePriority = instancePriority;
                }
                else
                {
                    m_InstancePriority.intValue = instancePriority;
                }
            }

            EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
            {
                EditorGUILayout.PropertyField(m_InstanceRoot);
                EditorGUILayout.PropertyField(m_UICamera);
                m_UIFormHelperInfo.Draw();
                m_UIGroupHelperInfo.Draw();
                EditorGUILayout.PropertyField(m_UIGroups, true);
            }
            EditorGUI.EndDisabledGroup();

            if (EditorApplication.isPlaying && IsPrefabInHierarchy(t.gameObject))
            {
                EditorGUILayout.LabelField("UI Group Count", t.UIGroupCount.ToString());
            }

            serializedObject.ApplyModifiedProperties();

            Repaint();
        }
Пример #18
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var showDatePickerProperty = property.FindPropertyRelative("m_showEditorCalendar");
            var showDatePicker         = showDatePickerProperty.boolValue;

            var serializedProperty = property.FindPropertyRelative("m_SerializedDate");

            SelectedDate = !String.IsNullOrEmpty(serializedProperty.stringValue) ? DateTime.Parse(serializedProperty.stringValue) : DateTime.Today;

            if (!String.IsNullOrEmpty(serializedProperty.stringValue))
            {
                if (!DateTime.TryParse(serializedProperty.stringValue, out SelectedDate))
                {
                    SelectedDate = DateTime.Today;
                }
            }
            else
            {
                SelectedDate = DateTime.Today;
            }

            if (buttonImage == null)
            {
                buttonImage = new GUIContent(Resources.Load("Sprites/Editor/Calendar_Editor") as Texture2D);
            }

            if (textStyle == null)
            {
                textStyle           = new GUIStyle(EditorStyles.textField);
                textStyle.fontSize  = 18;
                textStyle.alignment = TextAnchor.MiddleCenter;
            }

            EditorGUI.BeginProperty(position, label, property);

            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            var indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            var textFieldPosition = new Rect(position.x, position.y, 224, 24);
            var buttonPosition    = new Rect(position.x + 224, position.y, 40, 24);

            EditorGUI.BeginDisabledGroup(true);
            serializedProperty.stringValue = EditorGUI.TextField(textFieldPosition, serializedProperty.stringValue, textStyle);
            EditorGUI.EndDisabledGroup();
            if (GUI.Button(buttonPosition, buttonImage))
            {
                showDatePicker = !showDatePicker;
            }

            buttonPosition.x    += 48;
            buttonPosition.width = 24;

            if (GUI.Button(buttonPosition, "X"))
            {
                serializedProperty.stringValue = null;
                showDatePicker = false;
            }

            position.y += 24;

            if (showDatePicker)
            {
                showDatePicker = DrawDatePicker(position, serializedProperty, showDatePickerProperty);
            }

            EditorGUI.indentLevel = indent;

            showDatePickerProperty.boolValue = showDatePicker;

            EditorGUI.EndProperty();
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            if (target == null)
            {
                return;
            }

            bool isPrefab = PrefabUtility.GetPrefabType(target) == PrefabType.Prefab;

            EditorGUI.BeginDisabledGroup(isPrefab);

            EditorGUILayout.Space();
            if (GUILayout.Button(new GUIContent("Build Playback Prefab",
                                                isPrefab ? "Draw this object into the scene "
                                                + "before converting its raw recording "
                                                + "data into AnimationClip data."
                                                         : "")))
            {
                EditorApplication.delayCall += () =>
                {
                    target.BuildPlaybackPrefab(new ProgressBar());
                };
            }

            EditorGUI.EndDisabledGroup();

            EditorGUILayout.Space();
            _expandComponentTypes = EditorGUILayout.Foldout(_expandComponentTypes, "Component List");
            if (_expandComponentTypes)
            {
                EditorGUI.indentLevel++;

                var components = target.GetComponentsInChildren <Component>(includeInactive: true).
                                 Where(c => !(c is Transform || c is RectTransform)).
                                 Select(c => c.GetType()).
                                 Distinct().
                                 Where(m => m.Namespace != "Leap.Unity.Recording").
                                 OrderBy(m => m.Name);

                var groups = components.GroupBy(t => t.Namespace).OrderBy(g => g.Key);

                if (GUILayout.Button("Delete All Checked Components", GUILayout.Height(EditorGUIUtility.singleLineHeight * 2)))
                {
                    foreach (var c in components.Where(t => EditorPrefs.GetBool(getTypePrefKey(t), defaultValue: false)).
                             SelectMany(c => target.GetComponentsInChildren(c, includeInactive: true)))
                    {
                        Undo.DestroyObjectImmediate(c);
                    }
                }

                foreach (var group in groups)
                {
                    EditorGUILayout.Space();

                    using (new GUILayout.VerticalScope(EditorStyles.helpBox))
                    {
                        using (new GUILayout.HorizontalScope())
                        {
                            var uniform = group.Query().
                                          Select(getTypePrefKey).
                                          Select(k => EditorPrefs.GetBool(k, defaultValue: false)).
                                          UniformOrNone();

                            bool valueToUse = false;
                            uniform.Match(val =>
                            {
                                valueToUse = val;
                            },
                                          () =>
                            {
                                valueToUse = false;
                                EditorGUI.showMixedValue = true;
                            });

                            EditorGUI.BeginChangeCheck();
                            valueToUse = EditorGUILayout.ToggleLeft(group.Key ?? "Dev", valueToUse, EditorStyles.boldLabel);
                            if (EditorGUI.EndChangeCheck())
                            {
                                foreach (var t in group)
                                {
                                    EditorPrefs.SetBool(getTypePrefKey(t), valueToUse);
                                }
                            }

                            EditorGUI.showMixedValue = false;
                        }

                        EditorGUILayout.Space();
                        GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));

                        foreach (var type in group)
                        {
                            using (new GUILayout.HorizontalScope())
                            {
                                string prefKey  = getTypePrefKey(type);
                                bool   curValue = EditorPrefs.GetBool(prefKey, defaultValue: false);

                                EditorGUI.BeginChangeCheck();
                                curValue = EditorGUILayout.ToggleLeft(type.Name, curValue);
                                if (EditorGUI.EndChangeCheck())
                                {
                                    EditorPrefs.SetBool(prefKey, curValue);
                                }

                                if (GUILayout.Button("Select", GUILayout.ExpandWidth(false)))
                                {
                                    Selection.objects = target.GetComponentsInChildren(type, includeInactive: true).Select(t => t.gameObject).ToArray();
                                }

                                if (GUILayout.Button("Delete", GUILayout.ExpandWidth(false)))
                                {
                                    var toDelete = target.GetComponentsInChildren(type, includeInactive: true);
                                    foreach (var t in toDelete)
                                    {
                                        Undo.DestroyObjectImmediate(t);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #20
0
        public override void OnInspectorGUI()
        {
            MalbersEditor.DrawDescription("Pick Up Logic for Pickable Items");
            EditorGUILayout.BeginVertical(MalbersEditor.StyleGray);
            {
                MalbersEditor.DrawScript(script);
                serializedObject.Update();
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                EditorGUILayout.PropertyField(PickUpArea);
                EditorGUILayout.PropertyField(AutoPick);
                EditorGUILayout.PropertyField(m_HidePickArea);
                EditorGUILayout.EndVertical();


                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    EditorGUILayout.PropertyField(Holder);
                    if (Holder.objectReferenceValue)
                    {
                        EditorGUILayout.LabelField("Offsets", EditorStyles.boldLabel);
                        EditorGUILayout.PropertyField(PosOffset, new GUIContent("Position", "Position Local Offset to parent the item to the holder"));
                        EditorGUILayout.PropertyField(RotOffset, new GUIContent("Rotation", "Rotation Local Offset to parent the item to the holder"));
                    }
                }
                EditorGUILayout.EndVertical();


                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    EditorGUILayout.PropertyField(item);
                    EditorGUI.BeginDisabledGroup(true);
                    EditorGUILayout.PropertyField(FocusedItem);
                    EditorGUI.EndDisabledGroup();
                }
                EditorGUILayout.EndVertical();


                GUIStyle styles = new GUIStyle(EditorStyles.foldout)
                {
                    fontStyle = FontStyle.Bold
                };

                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                {
                    EditorGUI.indentLevel++;
                    ShowEvents.boolValue = EditorGUILayout.Foldout(ShowEvents.boolValue, "Events", styles);
                    EditorGUI.indentLevel--;

                    if (ShowEvents.boolValue)
                    {
                        EditorGUILayout.PropertyField(CanPickUp, new GUIContent("On Can Pick Item"));
                        EditorGUILayout.PropertyField(OnItem, new GUIContent("On Item Picked"));
                        EditorGUILayout.PropertyField(OnPicking);
                        EditorGUILayout.PropertyField(OnDropping);
                    }
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
                {
                    EditorGUILayout.PropertyField(DebugRadius);
                    EditorGUILayout.PropertyField(DebugColor, GUIContent.none, GUILayout.MaxWidth(40));
                }
                EditorGUILayout.EndHorizontal();

                serializedObject.ApplyModifiedProperties();
                EditorGUILayout.EndVertical();
            }
        }
        private void DrawValueFor(FieldDescription field, BytesAndOffset bytesAndOffset)
        {
            var typeDescription = _unpackedCrawl.typeDescriptions[field.typeIndex];

            switch (typeDescription.name)
            {
            case "System.Int32":
                GUILayout.Label(_primitiveValueReader.ReadInt32(bytesAndOffset).ToString());
                break;

            case "System.Int64":
                GUILayout.Label(_primitiveValueReader.ReadInt64(bytesAndOffset).ToString());
                break;

            case "System.UInt32":
                GUILayout.Label(_primitiveValueReader.ReadUInt32(bytesAndOffset).ToString());
                break;

            case "System.UInt64":
                GUILayout.Label(_primitiveValueReader.ReadUInt64(bytesAndOffset).ToString());
                break;

            case "System.Int16":
                GUILayout.Label(_primitiveValueReader.ReadInt16(bytesAndOffset).ToString());
                break;

            case "System.UInt16":
                GUILayout.Label(_primitiveValueReader.ReadUInt16(bytesAndOffset).ToString());
                break;

            case "System.Byte":
                GUILayout.Label(_primitiveValueReader.ReadByte(bytesAndOffset).ToString());
                break;

            case "System.SByte":
                GUILayout.Label(_primitiveValueReader.ReadSByte(bytesAndOffset).ToString());
                break;

            case "System.Char":
                GUILayout.Label(_primitiveValueReader.ReadChar(bytesAndOffset).ToString());
                break;

            case "System.Boolean":
                GUILayout.Label(_primitiveValueReader.ReadBool(bytesAndOffset).ToString());
                break;

            case "System.Single":
                GUILayout.Label(_primitiveValueReader.ReadSingle(bytesAndOffset).ToString());
                break;

            case "System.Double":
                GUILayout.Label(_primitiveValueReader.ReadDouble(bytesAndOffset).ToString());
                break;

            case "System.IntPtr":
                GUILayout.Label(_primitiveValueReader.ReadPointer(bytesAndOffset).ToString("X"));
                break;

            default:
                if (!typeDescription.isValueType)
                {
                    ThingInMemory item = GetThingAt(bytesAndOffset.ReadPointer());
                    if (item == null)
                    {
                        EditorGUI.BeginDisabledGroup(true);
                        GUILayout.Button("Null");
                        EditorGUI.EndDisabledGroup();
                    }
                    else
                    {
                        DrawLinks(new ThingInMemory[] { item }, 0);
                    }
                }
                else
                {
                    DrawFields(typeDescription, bytesAndOffset);
                }
                break;
            }
        }
Пример #22
0
    public override void OnGUI(Rect rect, SerializedProperty prop, GUIContent label)
    {
        SerializedProperty target = prop.FindPropertyRelative("ClassName");
        string             curSel = target.stringValue;

        List <string> strList = new List <string>();
        //List<string> strListOrder = new List<string>();
        SerializedObject serObj = target.serializedObject;
        //strListOrder.Add(curSel == "" ? "none" : curSel);

        int index = 0;

        if (serObj.targetObject is BindDataRoot)
        {
            var      path      = Application.dataPath + "/Plugins/DataModel/";
            Assembly ass       = Assembly.LoadFile(Path.Combine(path, "GameDataDefine.dll"));
            Type[]   types     = ass.GetTypes();
            int      tempIndex = 0;
            {
                var __array1       = types;
                var __arrayLength1 = __array1.Length;
                for (int __i1 = 0; __i1 < __arrayLength1; ++__i1)
                {
                    var t = (Type)__array1[__i1];
                    {
                        if (CheckClassProperChanged(t, 0))
                        {
                            strList.Add(t.Name);
                        }
                    }
                }
            }
        }
        else
        {
            Transform    tf   = null;
            BindDataRoot root = null;
            if (serObj.targetObject is InverseBinding)
            {
                InverseBinding tarObj = serObj.targetObject as InverseBinding;
                //tf = tarObj.gameObject.transform.parent;
                tf = tarObj.gameObject.transform;
            }
            else if (serObj.targetObject is UIClassBinding)
            {
                UIClassBinding tarObj = serObj.targetObject as UIClassBinding;
                //tf = tarObj.gameObject.transform.parent;
                tf = tarObj.gameObject.transform;
            }


            while (tf != null)
            {
                root = tf.gameObject.GetComponent <BindDataRoot>();
                if (root != null)
                {
                    {
                        var __list2      = root.BindingNamelList;
                        var __listCount2 = __list2.Count;
                        for (int __i2 = 0; __i2 < __listCount2; ++__i2)
                        {
                            var name = __list2[__i2];
                            {
                                strList.Add(name.ClassName);
                            }
                        }
                    }
                }
                tf = tf.parent;
            }
        }

        if (strList.Count == 0)
        {
            return;
        }
        strList.Sort();
        {
            var __list3      = strList;
            var __listCount3 = __list3.Count;
            for (int __i3 = 0; __i3 < __listCount3; ++__i3)
            {
                var s = __list3[__i3];
                {
                    if (curSel == s)
                    {
                        break;
                    }
                    index++;
                }
            }
        }
        GUI.changed = false;
        EditorGUI.BeginDisabledGroup(target.hasMultipleDifferentValues);
        int choice = EditorGUI.Popup(rect, "", index, strList.ToArray());

        if (GUI.changed && choice >= 0)
        {
            string str = strList[choice];
            target.stringValue = str;
        }
        EditorGUI.EndDisabledGroup();
    }
Пример #23
0
        void CreateMastersList()
        {
            List <DefaultAsset> mastersTextAssets = inkFile.masterInkAssets;

            mastersFileList = new ReorderableList(mastersTextAssets, typeof(DefaultAsset), false, true, false, false);
            mastersFileList.drawHeaderCallback = (Rect rect) => {
                EditorGUI.LabelField(rect, "Master Files");
            };
            mastersFileList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
                DefaultAsset masterAssetFile = ((List <DefaultAsset>)mastersFileList.list)[index];
                if (masterAssetFile == null)
                {
                    Debug.LogError("Ink file in masters list is null. This should never occur. Use Assets > Recompile Ink to fix this issue.");
                    EditorGUI.LabelField(rect, new GUIContent("Warning: Ink File in masters list is null. Use Assets > Recompile Ink to fix this issue."));
                    return;
                }
                InkFile masterInkFile = InkLibrary.GetInkFileWithFile(masterAssetFile);
                if (masterInkFile == null)
                {
                    Debug.LogError("Ink File for master file " + masterAssetFile + " not found. This should never occur. Use Assets > Recompile Ink to fix this issue.");
                    EditorGUI.LabelField(rect, new GUIContent("Warning: Ink File for master file " + masterAssetFile + " not found. Use Assets > Recompile Ink to fix this issue."));
                    return;
                }
                Rect iconRect = new Rect(rect.x, rect.y, 0, 16);
                if (masterInkFile.hasErrors || masterInkFile.hasWarnings)
                {
                    iconRect.width = 20;
                }
                Rect objectFieldRect = new Rect(iconRect.xMax, rect.y, rect.width - iconRect.width - 80, 16);
                Rect selectRect      = new Rect(objectFieldRect.xMax, rect.y, 80, 16);
                if (masterInkFile.hasErrors)
                {
                    EditorGUI.LabelField(iconRect, new GUIContent(InkBrowserIcons.errorIcon));
                }
                else if (masterInkFile.hasWarnings)
                {
                    EditorGUI.LabelField(iconRect, new GUIContent(InkBrowserIcons.warningIcon));
                }
                EditorGUI.BeginDisabledGroup(true);
                EditorGUI.ObjectField(objectFieldRect, masterAssetFile, typeof(Object), false);
                EditorGUI.EndDisabledGroup();
                if (GUI.Button(selectRect, "Select"))
                {
                    Selection.activeObject = masterAssetFile;
                }


                // foreach(var masterInkFile in inkFile.masterInkFiles) {
                //  EditorGUILayout.BeginHorizontal();
                //  if(masterInkFile.hasErrors) {
                //      GUILayout.Label(new GUIContent(InkBrowserIcons.errorIcon), GUILayout.Width(20));
                //  } else if(masterInkFile.hasWarnings) {
                //      GUILayout.Label(new GUIContent(InkBrowserIcons.warningIcon), GUILayout.Width(20));
                //  }
                //  EditorGUI.BeginDisabledGroup(true);
                //  EditorGUILayout.ObjectField("Master Ink File", masterInkFile.inkAsset, typeof(Object), false);
                //  EditorGUI.EndDisabledGroup();
                //  if(GUILayout.Button("Select", GUILayout.Width(80))) {
                //      Selection.activeObject = masterInkFile.inkAsset;
                //  }
                //  EditorGUILayout.EndHorizontal();
                // }
            };
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label = EditorGUI.BeginProperty(position, label, property);

        Action buttonAction      = Action.None;
        int    buttonActionIndex = 0;

        var keyArrayProperty   = property.FindPropertyRelative(KeysFieldName);
        var valueArrayProperty = property.FindPropertyRelative(ValuesFieldName);

        ConflictState conflictState = GetConflictState(property);

        if (conflictState.conflictIndex != -1)
        {
            keyArrayProperty.InsertArrayElementAtIndex(conflictState.conflictIndex);
            var keyProperty = keyArrayProperty.GetArrayElementAtIndex(conflictState.conflictIndex);
            SetPropertyValue(keyProperty, conflictState.conflictKey);
            keyProperty.isExpanded = conflictState.conflictKeyPropertyExpanded;

            valueArrayProperty.InsertArrayElementAtIndex(conflictState.conflictIndex);
            var valueProperty = valueArrayProperty.GetArrayElementAtIndex(conflictState.conflictIndex);
            SetPropertyValue(valueProperty, conflictState.conflictValue);
            valueProperty.isExpanded = conflictState.conflictValuePropertyExpanded;
        }

        var buttonWidth = s_buttonStyle.CalcSize(s_iconPlus).x;

        var labelPosition = position;

        labelPosition.height = EditorGUIUtility.singleLineHeight;
        if (property.isExpanded)
        {
            labelPosition.xMax -= s_buttonStyle.CalcSize(s_iconPlus).x;
        }

        EditorGUI.PropertyField(labelPosition, property, label, false);
        // property.isExpanded = EditorGUI.Foldout(labelPosition, property.isExpanded, label);
        if (property.isExpanded)
        {
            var buttonPosition = position;
            buttonPosition.xMin   = buttonPosition.xMax - buttonWidth;
            buttonPosition.height = EditorGUIUtility.singleLineHeight;
            EditorGUI.BeginDisabledGroup(conflictState.conflictIndex != -1);
            if (GUI.Button(buttonPosition, s_iconPlus, s_buttonStyle))
            {
                buttonAction      = Action.Add;
                buttonActionIndex = keyArrayProperty.arraySize;
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.indentLevel++;
            var linePosition = position;
            linePosition.y    += EditorGUIUtility.singleLineHeight;
            linePosition.xMax -= buttonWidth;

            foreach (var entry in EnumerateEntries(keyArrayProperty, valueArrayProperty))
            {
                var keyProperty   = entry.keyProperty;
                var valueProperty = entry.valueProperty;
                int i             = entry.index;

                float lineHeight = DrawKeyValueLine(keyProperty, valueProperty, linePosition, i);

                buttonPosition        = linePosition;
                buttonPosition.x      = linePosition.xMax;
                buttonPosition.height = EditorGUIUtility.singleLineHeight;
                if (GUI.Button(buttonPosition, s_iconMinus, s_buttonStyle))
                {
                    buttonAction      = Action.Remove;
                    buttonActionIndex = i;
                }

                if (i == conflictState.conflictIndex && conflictState.conflictOtherIndex == -1)
                {
                    var iconPosition = linePosition;
                    iconPosition.size = s_buttonStyle.CalcSize(s_warningIconNull);
                    GUI.Label(iconPosition, s_warningIconNull);
                }
                else if (i == conflictState.conflictIndex)
                {
                    var iconPosition = linePosition;
                    iconPosition.size = s_buttonStyle.CalcSize(s_warningIconConflict);
                    GUI.Label(iconPosition, s_warningIconConflict);
                }
                else if (i == conflictState.conflictOtherIndex)
                {
                    var iconPosition = linePosition;
                    iconPosition.size = s_buttonStyle.CalcSize(s_warningIconOther);
                    GUI.Label(iconPosition, s_warningIconOther);
                }


                linePosition.y += lineHeight;
            }

            EditorGUI.indentLevel--;
        }

        if (buttonAction == Action.Add)
        {
            keyArrayProperty.InsertArrayElementAtIndex(buttonActionIndex);
            valueArrayProperty.InsertArrayElementAtIndex(buttonActionIndex);
        }
        else if (buttonAction == Action.Remove)
        {
            DeleteArrayElementAtIndex(keyArrayProperty, buttonActionIndex);
            DeleteArrayElementAtIndex(valueArrayProperty, buttonActionIndex);
        }

        conflictState.conflictKey                   = null;
        conflictState.conflictValue                 = null;
        conflictState.conflictIndex                 = -1;
        conflictState.conflictOtherIndex            = -1;
        conflictState.conflictLineHeight            = 0f;
        conflictState.conflictKeyPropertyExpanded   = false;
        conflictState.conflictValuePropertyExpanded = false;

        foreach (var entry1 in EnumerateEntries(keyArrayProperty, valueArrayProperty))
        {
            var    keyProperty1      = entry1.keyProperty;
            int    i                 = entry1.index;
            object keyProperty1Value = GetPropertyValue(keyProperty1);

            if (keyProperty1Value == null)
            {
                var valueProperty1 = entry1.valueProperty;
                SaveProperty(keyProperty1, valueProperty1, i, -1, conflictState);
                DeleteArrayElementAtIndex(valueArrayProperty, i);
                DeleteArrayElementAtIndex(keyArrayProperty, i);

                break;
            }


            foreach (var entry2 in EnumerateEntries(keyArrayProperty, valueArrayProperty, i + 1))
            {
                var    keyProperty2      = entry2.keyProperty;
                int    j                 = entry2.index;
                object keyProperty2Value = GetPropertyValue(keyProperty2);

                if (ComparePropertyValues(keyProperty1Value, keyProperty2Value))
                {
                    var valueProperty2 = entry2.valueProperty;
                    SaveProperty(keyProperty2, valueProperty2, j, i, conflictState);
                    DeleteArrayElementAtIndex(keyArrayProperty, j);
                    DeleteArrayElementAtIndex(valueArrayProperty, j);

                    goto breakLoops;
                }
            }
        }
breakLoops:

        EditorGUI.EndProperty();
    }
Пример #25
0
        private void DrawEventListener(Rect rect, int index, bool isactive, bool isfocused)
        {
            SerializedProperty arrayElementAtIndex = this.m_ListenersArray.GetArrayElementAtIndex(index);

            ++rect.y;
            Rect[]             rowRects          = this.GetRowRects(rect);
            Rect               position1         = rowRects[0];
            Rect               position2         = rowRects[1];
            Rect               rect1             = rowRects[2];
            Rect               position3         = rowRects[3];
            SerializedProperty propertyRelative1 = arrayElementAtIndex.FindPropertyRelative("m_CallState");
            SerializedProperty propertyRelative2 = arrayElementAtIndex.FindPropertyRelative("m_Mode");
            SerializedProperty propertyRelative3 = arrayElementAtIndex.FindPropertyRelative("m_Arguments");
            SerializedProperty propertyRelative4 = arrayElementAtIndex.FindPropertyRelative("m_Target");
            SerializedProperty propertyRelative5 = arrayElementAtIndex.FindPropertyRelative("m_MethodName");
            Color              backgroundColor   = GUI.backgroundColor;

            GUI.backgroundColor = Color.white;
            EditorGUI.PropertyField(position1, propertyRelative1, GUIContent.none);
            EditorGUI.BeginChangeCheck();
            GUI.Box(position2, GUIContent.none);
            EditorGUI.PropertyField(position2, propertyRelative4, GUIContent.none);
            if (EditorGUI.EndChangeCheck())
            {
                propertyRelative5.stringValue = (string)null;
            }
            PersistentListenerMode persistentListenerMode = UnityEventDrawer.GetMode(propertyRelative2);

            if (propertyRelative4.objectReferenceValue == (UnityEngine.Object)null || string.IsNullOrEmpty(propertyRelative5.stringValue))
            {
                persistentListenerMode = PersistentListenerMode.Void;
            }
            SerializedProperty propertyRelative6;

            switch (persistentListenerMode)
            {
            case PersistentListenerMode.Object:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_ObjectArgument");
                break;

            case PersistentListenerMode.Int:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_IntArgument");
                break;

            case PersistentListenerMode.Float:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_FloatArgument");
                break;

            case PersistentListenerMode.String:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_StringArgument");
                break;

            case PersistentListenerMode.Bool:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_BoolArgument");
                break;

            default:
                propertyRelative6 = propertyRelative3.FindPropertyRelative("m_IntArgument");
                break;
            }
            string stringValue = propertyRelative3.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue;

            System.Type type = typeof(UnityEngine.Object);
            if (!string.IsNullOrEmpty(stringValue))
            {
                type = System.Type.GetType(stringValue, false) ?? typeof(UnityEngine.Object);
            }
            if (persistentListenerMode == PersistentListenerMode.Object)
            {
                EditorGUI.BeginChangeCheck();
                UnityEngine.Object @object = EditorGUI.ObjectField(position3, GUIContent.none, propertyRelative6.objectReferenceValue, type, true);
                if (EditorGUI.EndChangeCheck())
                {
                    propertyRelative6.objectReferenceValue = @object;
                }
            }
            else if (persistentListenerMode != PersistentListenerMode.Void && persistentListenerMode != PersistentListenerMode.EventDefined)
            {
                EditorGUI.PropertyField(position3, propertyRelative6, GUIContent.none);
            }
            EditorGUI.BeginDisabledGroup(propertyRelative4.objectReferenceValue == (UnityEngine.Object)null);
            EditorGUI.BeginProperty(rect1, GUIContent.none, propertyRelative5);
            GUIContent content;

            if (EditorGUI.showMixedValue)
            {
                content = EditorGUI.mixedValueContent;
            }
            else
            {
                StringBuilder stringBuilder = new StringBuilder();
                if (propertyRelative4.objectReferenceValue == (UnityEngine.Object)null || string.IsNullOrEmpty(propertyRelative5.stringValue))
                {
                    stringBuilder.Append("No Function");
                }
                else if (!UnityEventDrawer.IsPersistantListenerValid(this.m_DummyEvent, propertyRelative5.stringValue, propertyRelative4.objectReferenceValue, UnityEventDrawer.GetMode(propertyRelative2), type))
                {
                    string             str = "UnknownComponent";
                    UnityEngine.Object objectReferenceValue = propertyRelative4.objectReferenceValue;
                    if (objectReferenceValue != (UnityEngine.Object)null)
                    {
                        str = objectReferenceValue.GetType().Name;
                    }
                    stringBuilder.Append(string.Format("<Missing {0}.{1}>", (object)str, (object)propertyRelative5.stringValue));
                }
                else
                {
                    stringBuilder.Append(propertyRelative4.objectReferenceValue.GetType().Name);
                    if (!string.IsNullOrEmpty(propertyRelative5.stringValue))
                    {
                        stringBuilder.Append(".");
                        if (propertyRelative5.stringValue.StartsWith("set_"))
                        {
                            stringBuilder.Append(propertyRelative5.stringValue.Substring(4));
                        }
                        else
                        {
                            stringBuilder.Append(propertyRelative5.stringValue);
                        }
                    }
                }
                content = GUIContent.Temp(stringBuilder.ToString());
            }
            if (GUI.Button(rect1, content, EditorStyles.popup))
            {
                UnityEventDrawer.BuildPopupList(propertyRelative4.objectReferenceValue, this.m_DummyEvent, arrayElementAtIndex).DropDown(rect1);
            }
            EditorGUI.EndProperty();
            EditorGUI.EndDisabledGroup();
            GUI.backgroundColor = backgroundColor;
        }
Пример #26
0
        /// <summary> Panel to display Output options </summary>
        /// <param name="inlineHelp">Should help be displayed?</param>
        void OutputPanel(bool inlineHelp)
        {
            ++EditorGUI.indentLevel;
            m_editorUtils.EnumPopupLocalized("mOutputType", "OutputType_", m_outputTypeProp, inlineHelp);
            OutputType outputType = ( OutputType)System.Enum.GetValues(typeof(OutputType)).GetValue(m_outputTypeProp.enumValueIndex);

            outputBool.target = outputType != OutputType.STRAIGHT;
            if (EditorGUILayout.BeginFadeGroup(outputBool.faded))
            {
                EditorGUI.BeginChangeCheck();
                Object prefab = m_editorUtils.ObjectField("mOutputPrefab", m_outputPrefabProp.objectReferenceValue, typeof(GameObject), false, inlineHelp);
                if (EditorGUI.EndChangeCheck())
                {
                    m_outputPrefabProp.objectReferenceValue = prefab;
                }
                if (m_outputPrefabProp != null && m_outputPrefabProp.objectReferenceValue != null)
                {
                    AudioSource prefabSource = ((GameObject)m_outputPrefabProp.objectReferenceValue).GetComponent <AudioSource>();
                    if (prefabSource == null)
                    {
                        EditorGUILayout.HelpBox(m_editorUtils.GetContent("PrefabNoSource").text, MessageType.Info);
                    }
                    else
                    {
                        bool spatialize   = false;
                        bool spatialblend = false;
                        if (prefabSource.spatialize == false)
                        {
                            spatialize = true;
                        }
                        if (prefabSource.spatialBlend < 1f)
                        {
                            spatialblend = true;
                        }
                        if (spatialize || spatialblend)
                        {
                            EditorGUILayout.HelpBox(m_editorUtils.GetContent("PrefabSettingsWarningPrefix").text
                                                    + (spatialize ? m_editorUtils.GetContent("PrefabSettingsWarningSpatialize").text : "")
                                                    + (spatialblend ? m_editorUtils.GetContent("PrefabSettingsWarningSpatialBlend").text : "")
                                                    , MessageType.Warning);
                            if (m_editorUtils.Button("PrefabSettingsButton"))
                            {
                                prefabSource.spatialize   = true;
                                prefabSource.spatialBlend = 1.0f;
                                EditorUtility.SetDirty(m_outputPrefabProp.objectReferenceValue);
#if UNITY_2018_3_OR_NEWER
                                PrefabUtility.SavePrefabAsset(prefabSource.gameObject);
#else
                                PrefabUtility.ReplacePrefab(prefabSource.gameObject, m_outputPrefabProp.objectReferenceValue);
#endif
                            }
                        }
                    }
                }
                Rect    r    = EditorGUILayout.GetControlRect();
                float[] vals = new float[2] {
                    m_outputDistanceProp.vector2Value.x, m_outputDistanceProp.vector2Value.y
                };
                EditorGUI.BeginChangeCheck();
                EditorGUI.MultiFloatField(r, m_editorUtils.GetContent("mOutputDistance"), new GUIContent[] { new GUIContent(""), new GUIContent("-") }, vals);
                if (EditorGUI.EndChangeCheck())
                {
                    m_outputDistanceProp.vector2Value = new Vector2(vals[0], vals[1]);
                }
                m_editorUtils.SliderRange("mOutputVerticalAngle", m_outputVerticalAngleProp, inlineHelp, -180, 180);
                m_editorUtils.SliderRange("mOutputHorizontalAngle", m_outputHorizontalAngleProp, inlineHelp, -180, 180);
                m_outputFollowPosition.boolValue = m_editorUtils.Toggle("mOutputFollowPosition", m_outputFollowPosition.boolValue, inlineHelp);
                EditorGUI.BeginDisabledGroup(!m_outputFollowPosition.boolValue);
                m_outputFollowRotation.boolValue = m_editorUtils.Toggle("mOutputFollowRotation", m_outputFollowRotation.boolValue, inlineHelp);
                EditorGUI.EndDisabledGroup();
            }
            EditorGUILayout.EndFadeGroup();
            --EditorGUI.indentLevel;
        }
    /// <summary>
    /// Custom Inspector
    /// </summary>
    public override void OnInspectorGUI()
    {
        // Start custom Inspector
        serializedObject.Update();
        EditorGUI.BeginChangeCheck();
        m_target.layerIndex = m_reorderableTilemapLayerList.index;

        if (m_target.toolIndex > 0 && m_target.toolIndex < 5)
        {
            Tools.hidden = true;
        }
        else
        {
            Tools.hidden = false;
        }
        //
        // References
        //
        m_showReferencesGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showReferencesGroup.isExpanded, "References");
        if (m_showReferencesGroup.isExpanded)
        {
            GUILayout.Space(1);
            // Standard diffuse shader
            GUI.color = m_greenColor;
            if (!m_legacyShader.objectReferenceValue)
            {
                GUI.color = m_redColor;
            }
            EditorGUILayout.PropertyField(m_legacyShader, m_guiContent[7]);

            // Universal diffuse shader
            GUI.color = m_greenColor;
            if (!m_universalShader.objectReferenceValue)
            {
                GUI.color = m_redColor;
            }
            EditorGUILayout.PropertyField(m_universalShader, m_guiContent[8]);
            GUI.color = Color.white;
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        //
        // Settings
        //
        m_showSettingsGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showSettingsGroup.isExpanded, "Settings");
        if (m_showSettingsGroup.isExpanded)
        {
            GUILayout.Space(1);
            // Render pipeline
            EditorGUILayout.PropertyField(m_renderPipeline, m_guiContent[9]);
            if (m_target.renderPipeline == TilemapSystemPipeline.Universal)
            {
                EditorGUILayout.HelpBox("Universal Render Pipeline is still a work in progress and is not fully functional.", MessageType.Info);
            }

            // Tilemap size
            EditorGUILayout.IntPopup(m_tilesetSize, m_tilesetSizeContentArray, m_tilesetSizeArray, m_guiContent[16]);

            // Grid size
            EditorGUILayout.BeginVertical("Box");
            EditorGUILayout.LabelField(m_guiContent[0]);
            m_gridMapSize.x = EditorGUILayout.IntField(m_guiContent[1], (int)m_target.gridMapSize.x);
            m_gridMapSize.y = EditorGUILayout.IntField(m_guiContent[2], (int)m_target.gridMapSize.y);
            EditorGUILayout.EndVertical();

            // Layer list
            m_reorderableTilemapLayerList.DoLayoutList();
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        //
        // Data
        //
        m_showDataGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showDataGroup.isExpanded, "Data");
        if (m_showDataGroup.isExpanded)
        {
            GUILayout.Space(1);
            if (m_reorderableTilemapLayerList.count > 0)
            {
                EditorGUI.BeginDisabledGroup(true);
                // Tilemap data
                if (!m_tilemapData.objectReferenceValue)
                {
                    GUI.color = m_redColor;
                }
                EditorGUI.ObjectField(EditorGUILayout.GetControlRect(), m_tilemapData, m_guiContent[6]);
                GUI.color = Color.white;
                // Tilemap texture field
                if (!m_target.tilemapTexture)
                {
                    GUI.color = m_redColor;
                }
                EditorGUI.ObjectField(EditorGUILayout.GetControlRect(), m_guiContent[13], m_target.tilemapTexture, typeof(Texture3D), false);
                GUI.color = Color.white;
                // Tileset texture field
                if (!m_target.tilesetTexture)
                {
                    GUI.color = m_redColor;
                }
                EditorGUI.ObjectField(EditorGUILayout.GetControlRect(), m_guiContent[15], m_target.tilesetTexture, typeof(Texture3D), false);
                GUI.color = Color.white;
                // Array texture field
                if (!m_target.layerArrayTexture)
                {
                    GUI.color = m_redColor;
                }
                EditorGUI.ObjectField(EditorGUILayout.GetControlRect(), m_guiContent[17], m_target.layerArrayTexture, typeof(Texture2D), false);
                GUI.color = Color.white;
                // Render material field
                if (!m_target.renderMaterial)
                {
                    GUI.color = m_redColor;
                }
                EditorGUI.ObjectField(EditorGUILayout.GetControlRect(), m_guiContent[14], m_target.renderMaterial, typeof(Material), false);
                GUI.color = Color.white;
                EditorGUI.EndDisabledGroup();

                // Button
                if (GUILayout.Button("Generate Tilemap Data"))
                {
                    m_target.GenerateTilemapData();
                    if (m_target.tilemapData)
                    {
                        TilePalette[] palettes   = new TilePalette[m_target.tilemapLayerList.Count];
                        int[]         tilesCount = new int[m_target.tilemapLayerList.Count];
                        for (int i = 0; i < palettes.Length; i++)
                        {
                            palettes[i] = m_target.tilemapLayerList[i].tilePalette;
                            if (palettes[i])
                            {
                                tilesCount[i] = m_target.tilemapLayerList[i].tilePalette.tilesCount;
                            }
                            else
                            {
                                tilesCount[i] = 0;
                            }
                        }

                        m_target.tilemapData.settingsState  = new TilemapSettings(m_target.tilemapLayerList.Count, tilesCount, palettes, (int)m_gridMapSize.x, (int)m_gridMapSize.y, m_tilesetSize.intValue);
                        m_target.tilemapData.layerIntensity = new float[m_target.tilemapLayerList.Count];
                    }
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        //
        // Painting
        //
        m_showPantingGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showPantingGroup.isExpanded, "Painting");
        if (m_showPantingGroup.isExpanded)
        {
            if (m_reorderableTilemapLayerList.count > 0 && m_target.layerIndex >= 0 && m_target.tilemapLayerList.Count > 0)
            {
                if (m_tilemapData.objectReferenceValue)
                {
                    // Tile palette field
                    EditorGUILayout.BeginVertical("Box");
                    m_tilePalette = m_reorderableTilemapLayerList.serializedProperty.GetArrayElementAtIndex(m_target.layerIndex).FindPropertyRelative("tilePalette");
                    GUI.color     = m_greenColor;
                    if (!m_tilePalette.objectReferenceValue)
                    {
                        GUI.color = m_redColor;
                    }
                    EditorGUILayout.PropertyField(m_tilePalette, m_guiContent[5]);
                    GUI.color = Color.white;
                    EditorGUILayout.EndVertical();

                    if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette)
                    {
                        // Painting mode
                        EditorGUILayout.BeginVertical("Box");
                        EditorGUILayout.PropertyField(m_paintingMode, m_guiContent[10]);

                        // Auto tile layout popup
                        if (m_target.paintingMode == TilemapSystemPaintingMode.AutoTiles)
                        {
                            m_autoTileElements = GetAutoTileElements();

                            if (m_autoTileElements.Length > 0)
                            {
                                m_autoTileLayoutIndex          = m_reorderableTilemapLayerList.serializedProperty.GetArrayElementAtIndex(m_target.layerIndex).FindPropertyRelative("layoutIndex");
                                m_autoTileLayoutIndex.intValue = EditorGUILayout.Popup(m_guiContent[17], m_autoTileLayoutIndex.intValue, m_autoTileElements);
                            }
                            else
                            {
                                EditorGUILayout.HelpBox("The Auto Tile list is empty. Please, set some auto tile layout first.", MessageType.Error);
                            }
                        }
                        EditorGUILayout.EndVertical();
                        GUILayout.Space(-3);

                        if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette.tilesCount > 0)
                        {
                            EditorGUILayout.BeginVertical("Box");
                            if (m_target.tilesetTexture)
                            {
                                if (CanPaint())
                                {
                                    // Reset layer button
                                    if (GUILayout.Button("Reset This Layer Using the Selected Tile"))
                                    {
                                        // Register the texture in the undo stack
                                        Undo.RegisterCompleteObjectUndo(m_target.tilemapTexture, "Tilemap Change");
                                        m_target.ResetLayer(m_target.layerIndex);
                                    }

                                    // Toolbar
                                    EditorGUILayout.BeginHorizontal();
                                    m_isPicking = m_target.toolIndex == 1 ? true : false;
                                    if (GUILayout.Toggle(m_isPicking, m_paintingToolIcons[0], EditorStyles.miniButtonLeft))
                                    {
                                        m_target.toolIndex = 1;
                                    }
                                    else if (m_target.toolIndex == 1)
                                    {
                                        m_target.toolIndex = 0;
                                    }

                                    m_isPainting = m_target.toolIndex == 2 ? true : false;
                                    if (GUILayout.Toggle(m_isPainting, m_paintingToolIcons[1], EditorStyles.miniButtonMid))
                                    {
                                        m_target.toolIndex = 2;
                                    }
                                    else if (m_target.toolIndex == 2)
                                    {
                                        m_target.toolIndex = 0;
                                    }

                                    m_isFilling = m_target.toolIndex == 3 ? true : false;
                                    if (GUILayout.Toggle(m_isFilling, m_paintingToolIcons[2], EditorStyles.miniButtonMid))
                                    {
                                        m_target.toolIndex = 3;
                                    }
                                    else if (m_target.toolIndex == 3)
                                    {
                                        m_target.toolIndex = 0;
                                    }

                                    m_isErasing = m_target.toolIndex == 4 ? true : false;
                                    if (GUILayout.Toggle(m_isErasing, m_paintingToolIcons[3], EditorStyles.miniButtonRight))
                                    {
                                        m_target.toolIndex = 4;
                                    }
                                    else if (m_target.toolIndex == 4)
                                    {
                                        m_target.toolIndex = 0;
                                    }
                                    EditorGUILayout.EndHorizontal();
                                }
                                else
                                {
                                    EditorGUILayout.HelpBox("It looks like you have changed some settings. Please, regenerate the Tilemap Data to update the 3D Textures.", MessageType.Error);
                                }
                            }
                            else
                            {
                                EditorGUILayout.HelpBox("There is no Tileset Texture yet. Please, regenerate the Tilemap Data again to create the 3D Tileset texture so you can start painting.", MessageType.Error);
                            }

                            // Tile grid
                            m_scrollPos = EditorGUILayout.BeginScrollView(m_scrollPos);
                            EditorGUILayout.LabelField("", GUILayout.Width(442));
                            GUILayout.Space(-20);
                            m_buttonIndex = 0;

                            // Start the selectable loop
                            for (int vertical = 0; vertical < 256;)
                            {
                                m_controlRect = EditorGUILayout.GetControlRect(GUILayout.Width(24), GUILayout.Height(24));

                                EditorGUILayout.BeginHorizontal();
                                for (int horizontal = 0; horizontal < 16; horizontal++)
                                {
                                    // Get the tile texture
                                    m_tileTexture = m_target.tilemapLayerList[m_target.layerIndex].tilePalette.temporaryTileTextureArray[vertical] ? m_target.tilemapLayerList[m_target.layerIndex].tilePalette.temporaryTileTextureArray[vertical] : emptyIconTexture;

                                    // Draw the selectable button
                                    m_isSelected = m_target.tileIndex == m_buttonIndex ? true : false;
                                    if (GUI.Toggle(m_controlRect, m_isSelected, GUIContent.none, GUI.skin.button))
                                    {
                                        m_target.tileIndex = m_buttonIndex;
                                    }

                                    // Draw the tile texture
                                    if (m_isSelected)
                                    {
                                        GUI.color = m_selectedTileColor;
                                    }
                                    GUI.DrawTexture(m_controlRect, m_tileTexture, ScaleMode.StretchToFill, true, 0);
                                    GUI.color = Color.white;

                                    m_controlRect.x += 28;
                                    vertical++;
                                    m_buttonIndex++;
                                }

                                EditorGUILayout.EndHorizontal();
                            }

                            EditorGUILayout.EndScrollView();
                            EditorGUILayout.EndVertical();
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("The Tile Palette used in this layer is empty. Please, add the tiles to the Tile Palette first.", MessageType.Error);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("The tile palette of this layer is missing! Add a Tile Palette to start painting.", MessageType.Error);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("There is no tilemap data created yet! Generate the Tilemap Data.", MessageType.Error);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        //
        // Auto tiles
        //
        m_showAutoTileGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showAutoTileGroup.isExpanded, "Auto Tiles");
        if (m_showAutoTileGroup.isExpanded)
        {
            if (m_reorderableTilemapLayerList.count > 0 && m_target.layerIndex >= 0 && m_target.tilemapLayerList.Count > 0)
            {
                if (m_tilemapData.objectReferenceValue)
                {
                    if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette)
                    {
                        if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette.tilesCount > 0)
                        {
                            // Editor stuff here
                            GUILayout.Space(3);
                            m_autoTileDictionary[m_target.layerIndex].DoLayoutList();
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("The Tile Palette used in this layer is empty. Please, add the tiles to the Tile Palette first.", MessageType.Error);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("The tile palette of this layer is missing! Add a Tile Palette to start painting.", MessageType.Error);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("There is no tilemap data created yet! Generate the Tilemap Data.", MessageType.Error);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        //
        // Random tile painting
        //
        EditorGUI.BeginDisabledGroup(true);
        m_showRandomTilePaintingGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showRandomTilePaintingGroup.isExpanded, "Random Tile Painting");
        if (m_showRandomTilePaintingGroup.isExpanded)
        {
            if (m_reorderableTilemapLayerList.count > 0 && m_target.layerIndex >= 0 && m_target.tilemapLayerList.Count > 0)
            {
                if (m_tilemapData.objectReferenceValue)
                {
                    if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette)
                    {
                        if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette.tilesCount > 0)
                        {
                            // Editor stuff here
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("The Tile Palette used in this layer is empty. Please, add the tiles to the Tile Palette first.", MessageType.Error);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("The tile palette of this layer is missing! Add a Tile Palette to start painting.", MessageType.Error);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("There is no tilemap data created yet! Generate the Tilemap Data.", MessageType.Error);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();

        // Random tiles
        m_showRandomizeTileGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showRandomizeTileGroup.isExpanded, "Randomize Tiles");
        if (m_showRandomizeTileGroup.isExpanded)
        {
            if (m_reorderableTilemapLayerList.count > 0 && m_target.layerIndex >= 0 && m_target.tilemapLayerList.Count > 0)
            {
                if (m_tilemapData.objectReferenceValue)
                {
                    if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette)
                    {
                        if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette.tilesCount > 0)
                        {
                            // Editor stuff here
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("The Tile Palette used in this layer is empty. Please, add the tiles to the Tile Palette first.", MessageType.Error);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("The tile palette of this layer is missing! Add a Tile Palette to start painting.", MessageType.Error);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("There is no tilemap data created yet! Generate the Tilemap Data.", MessageType.Error);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();

        // Tile brushes
        m_showTileBrushesGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showTileBrushesGroup.isExpanded, "Tile Brushes");
        if (m_showTileBrushesGroup.isExpanded)
        {
            if (m_reorderableTilemapLayerList.count > 0 && m_target.layerIndex >= 0 && m_target.tilemapLayerList.Count > 0)
            {
                if (m_tilemapData.objectReferenceValue)
                {
                    if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette)
                    {
                        if (m_target.tilemapLayerList[m_target.layerIndex].tilePalette.tilesCount > 0)
                        {
                            // Editor stuff here
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("The Tile Palette used in this layer is empty. Please, add the tiles to the Tile Palette first.", MessageType.Error);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("The tile palette of this layer is missing! Add a Tile Palette to start painting.", MessageType.Error);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("There is no tilemap data created yet! Generate the Tilemap Data.", MessageType.Error);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("There is no layer created yet! Create a tilemap layer.", MessageType.Error);
            }
        }
        EditorGUILayout.EndFoldoutHeaderGroup();
        EditorGUI.EndDisabledGroup();

        // About group
        m_showAboutGroup.isExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(m_showAboutGroup.isExpanded, "About");
        if (m_showAboutGroup.isExpanded)
        {
            EditorGUILayout.HelpBox("3D Tilemap System v1.0.1 by Seven Stars Games", MessageType.None);
            if (GUILayout.Button(m_guiContent[18]))
            {
                Application.OpenURL("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=S8AB7CVH5VMZS&source=url");
            }
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("My other assets you may like:");
            if (GUILayout.Button(m_guiContent[19]))
            {
                Application.OpenURL("https://assetstore.unity.com/packages/tools/particles-effects/azure-sky-dynamic-skybox-36050");
            }
            if (GUILayout.Button(m_guiContent[20]))
            {
                Application.OpenURL("https://assetstore.unity.com/packages/vfx/shaders/azure-sky-lite-89858");
            }
        }

        // Update layer intensity when there is a change in the Inspector
        if (m_target.tilemapData)
        {
            if (NeedUpdateLayerIntensity())
            {
                m_target.UpdateLayerSettings();
                m_target.tilemapData.layerIntensity = new float[m_target.tilemapLayerList.Count];
                for (int i = 0; i < m_target.tilemapLayerList.Count; i++)
                {
                    m_target.tilemapData.layerIntensity[i] = m_target.tilemapLayerList[i].intensity;
                }
            }
        }

        // End custom Inspector
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(m_target, "3D Tilemap System");
            serializedObject.ApplyModifiedProperties();
            m_target.gridMapSize = m_gridMapSize;
            m_target.UpdateMaterialSettings();
        }
    }
    public override void OnGUI(Rect rect, SerializedProperty prop, GUIContent label)
    {
        Undo.RecordObject(prop.serializedObject.targetObject, "Delegate Selection");

        SerializedProperty targetProp = prop.FindPropertyRelative("mTarget");
        SerializedProperty methodProp = prop.FindPropertyRelative("mMethodName");

        MonoBehaviour target     = targetProp.objectReferenceValue as MonoBehaviour;
        string        methodName = methodProp.stringValue;

        EditorGUI.indentLevel = prop.depth;
        EditorGUI.LabelField(rect, label);

        Rect lineRect = rect;

        lineRect.yMin = rect.yMin + lineHeight;
        lineRect.yMax = lineRect.yMin + lineHeight;

        EditorGUI.indentLevel = targetProp.depth;
        target = EditorGUI.ObjectField(lineRect, "Notify", target, typeof(MonoBehaviour), true) as MonoBehaviour;
        targetProp.objectReferenceValue = target;

        if (target != null && target.gameObject != null)
        {
            GameObject   go   = target.gameObject;
            List <Entry> list = EventDelegateEditor.GetMethods(go);

            int index  = 0;
            int choice = 0;

            EventDelegate del = new EventDelegate();
            del.target     = target;
            del.methodName = methodName;
            string[] names = PropertyReferenceDrawer.GetNames(list, del.ToString(), out index);

            lineRect.yMin += lineHeight;
            lineRect.yMax += lineHeight;
            choice         = EditorGUI.Popup(lineRect, "Method", index, names);

            if (choice > 0)
            {
                if (choice != index)
                {
                    Entry entry = list[choice - 1];
                    target     = entry.target as MonoBehaviour;
                    methodName = entry.name;
                    targetProp.objectReferenceValue = target;
                    methodProp.stringValue          = methodName;
                }
            }

            // Unfortunately Unity's property drawers only work with UnityEngine.Object-derived types.
            // This means that arrays are not supported. And since EventDelegate is not derived from
            // UnityEngine.Object either, it means that it's not possible to modify the parameter array.
            EditorGUI.BeginDisabledGroup(true);

            //SerializedProperty paramProp = prop.FindPropertyRelative("mParameters");
            EventDelegate.Parameter[] ps = del.parameters;

            if (ps != null)
            {
                for (int i = 0; i < ps.Length; ++i)
                {
                    EventDelegate.Parameter param = ps[i];
                    lineRect.yMin += lineHeight;
                    lineRect.yMax += lineHeight;
                    param.obj      = EditorGUI.ObjectField(lineRect, "   Arg " + i, param.obj, typeof(Object), true);
                    if (param.obj == null)
                    {
                        continue;
                    }

                    GameObject  selGO = null;
                    System.Type type  = param.obj.GetType();
                    if (type == typeof(GameObject))
                    {
                        selGO = param.obj as GameObject;
                    }
                    else if (type.IsSubclassOf(typeof(Component)))
                    {
                        selGO = (param.obj as Component).gameObject;
                    }

                    if (selGO != null)
                    {
                        // Parameters must be exact -- they can't be converted like property bindings
                        PropertyReferenceDrawer.filter     = param.expectedType;
                        PropertyReferenceDrawer.canConvert = false;
                        List <PropertyReferenceDrawer.Entry> ents = PropertyReferenceDrawer.GetProperties(selGO, true, false);

                        int      selection;
                        string[] props = EventDelegateEditor.GetNames(ents, NGUITools.GetFuncName(param.obj, param.field), out selection);

                        lineRect.yMin += lineHeight;
                        lineRect.yMax += lineHeight;
                        int newSel = EditorGUI.Popup(lineRect, " ", selection, props);

                        if (newSel != selection)
                        {
                            if (newSel == 0)
                            {
                                param.obj   = selGO;
                                param.field = null;
                            }
                            else
                            {
                                param.obj   = ents[newSel - 1].target;
                                param.field = ents[newSel - 1].name;
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(param.field))
                    {
                        param.field = null;
                    }

                    PropertyReferenceDrawer.filter     = typeof(void);
                    PropertyReferenceDrawer.canConvert = true;
                }
            }

            EditorGUI.EndDisabledGroup();
        }
        //else paramProp.objectReferenceValue = null;
    }
Пример #29
0
        public override void OnInspectorGUI()
        {
            var style = new GUIStyle(EditorStyles.toolbar);

            style.fixedHeight   = 0f;
            style.stretchHeight = true;

            var backStyle = new GUIStyle(EditorStyles.label);

            backStyle.normal.background = Texture2D.whiteTexture;

            var slice      = new ME.ECS.DataConfigs.DataConfigSlice();
            var isMultiple = false;

            if (this.targets.Length > 1)
            {
                slice      = ME.ECS.DataConfigs.DataConfigSlice.Distinct(this.targets.Cast <ME.ECS.DataConfigs.DataConfig>().ToArray());
                isMultiple = true;
            }
            else
            {
                var config = (ME.ECS.DataConfigs.DataConfig) this.target;
                slice = new ME.ECS.DataConfigs.DataConfigSlice()
                {
                    configs = new [] {
                        config
                    },
                    structComponentsDataTypeIds = config.structComponentsDataTypeIds,
                    componentsTypeIds           = config.componentsTypeIds
                };
            }

            var usedComponentsAll = new System.Collections.Generic.HashSet <System.Type>();

            foreach (var cfg in slice.configs)
            {
                var componentTypes = cfg.GetStructComponentTypes();
                foreach (var cType in componentTypes)
                {
                    if (usedComponentsAll.Contains(cType) == false)
                    {
                        usedComponentsAll.Add(cType);
                    }
                }

                if (DataConfigEditor.worldEditors.TryGetValue(cfg, out var worldEditor) == false)
                {
                    worldEditor = new WorldsViewerEditor.WorldEditor();
                    DataConfigEditor.worldEditors.Add(cfg, worldEditor);
                }
            }

            if (isMultiple == true)
            {
                GUILayoutExt.DrawHeader("The same components:");

                GUILayoutExt.Padding(8f, () => {
                    var kz = 0;
                    for (int i = 0; i < slice.structComponentsDataTypeIds.Length; ++i)
                    {
                        var typeId     = slice.structComponentsDataTypeIds[i];
                        var component  = slice.configs[0].GetByTypeId(typeId);
                        var components = slice.configs.Select(x => x.GetByTypeId(typeId)).ToArray();

                        var backColor       = GUI.backgroundColor;
                        GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                        GUILayout.BeginVertical(backStyle);
                        {
                            GUI.backgroundColor = backColor;
                            var editor          = WorldsViewerEditor.GetEditor(components);
                            if (editor != null)
                            {
                                EditorGUI.BeginChangeCheck();
                                editor.OnDrawGUI();
                                if (EditorGUI.EndChangeCheck() == true)
                                {
                                    slice.Set(typeId, components);
                                    this.Save(slice.configs);
                                }
                            }
                            else
                            {
                                var componentName = GUILayoutExt.GetStringCamelCaseSpace(component.GetType().Name);
                                var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                                if (fieldsCount == 0)
                                {
                                    EditorGUI.BeginDisabledGroup(true);
                                    EditorGUILayout.Toggle(componentName, true);
                                    EditorGUI.EndDisabledGroup();
                                }
                                else if (fieldsCount == 1)
                                {
                                    var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, components, componentName);
                                    if (changed == true)
                                    {
                                        slice.Set(typeId, components);
                                        this.Save(slice.configs);
                                    }
                                }
                                else
                                {
                                    GUILayout.BeginHorizontal();
                                    {
                                        GUILayout.Space(18f);
                                        GUILayout.BeginVertical();
                                        {
                                            var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                            var foldout = EditorPrefs.GetBool(key, true);
                                            GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, components);
                                                if (changed == true)
                                                {
                                                    slice.Set(typeId, components);
                                                    this.Save(slice.configs);
                                                }
                                            });
                                            EditorPrefs.SetBool(key, foldout);
                                        }
                                        GUILayout.EndVertical();
                                    }
                                    GUILayout.EndHorizontal();
                                }
                            }

                            GUILayoutExt.DrawComponentHelp(component.GetType());
                        }
                        GUILayout.EndVertical();

                        GUILayoutExt.Separator();
                    }
                });

                GUILayoutExt.DrawAddComponentMenu(usedComponentsAll, (addType, isUsed) => {
                    foreach (var dataConfigInner in slice.configs)
                    {
                        if (isUsed == true)
                        {
                            usedComponentsAll.Remove(addType);
                            for (int i = 0; i < dataConfigInner.structComponents.Length; ++i)
                            {
                                if (dataConfigInner.structComponents[i].GetType() == addType)
                                {
                                    var list = dataConfigInner.structComponents.ToList();
                                    list.RemoveAt(i);
                                    dataConfigInner.structComponents = list.ToArray();
                                    dataConfigInner.OnScriptLoad();
                                    this.Save(dataConfigInner);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            usedComponentsAll.Add(addType);
                            System.Array.Resize(ref dataConfigInner.structComponents, dataConfigInner.structComponents.Length + 1);
                            dataConfigInner.structComponents[dataConfigInner.structComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                            dataConfigInner.OnScriptLoad();
                            this.Save(dataConfigInner);
                        }
                    }
                });

                return;
            }

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Add Struct Components:");
            GUILayoutExt.Separator();

            var dataConfig = (ME.ECS.DataConfigs.DataConfig) this.target;

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.structComponents;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, Registry>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle, GUILayout.MinHeight(24f));
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IStructComponent>();
                                dataConfig.structComponents[registry.index] = component;
                                this.Save(dataConfig);
                            }
                        }
                        else
                        {
                            var componentName = component.GetType().Name;
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.structComponents[registry.index] = component;
                                    this.Save(dataConfig);
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            ++EditorGUI.indentLevel;
                                            var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.structComponents[registry.index] = component;
                                                this.Save(dataConfig);
                                            }
                                            --EditorGUI.indentLevel;
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }

                        GUILayoutExt.DrawComponentHelp(component.GetType());
                        this.DrawComponentTemplatesUsage(dataConfig, component);
                    }
                    GUILayout.EndVertical();

                    var lastRect = GUILayoutUtility.GetLastRect();
                    if (Event.current.type == EventType.ContextClick && lastRect.Contains(Event.current.mousePosition) == true)
                    {
                        var index = registry.index;

                        var menu = new GenericMenu();
                        if (this.CanMove(dataConfig, index, index - 1) == true)
                        {
                            menu.AddItem(new GUIContent("Move Up"), false, () => { this.MoveElement(dataConfig, index, index - 1); });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Move Up"));
                        }

                        if (this.CanMove(dataConfig, index, index + 1) == true)
                        {
                            menu.AddItem(new GUIContent("Move Down"), false, () => { this.MoveElement(dataConfig, index, index + 1); });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Move Down"));
                        }

                        menu.ShowAsContext();
                    }

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.structComponents.Length; ++i)
                        {
                            if (dataConfig.structComponents[i].GetType() == addType)
                            {
                                var list = dataConfig.structComponents.ToList();
                                list.RemoveAt(i);
                                dataConfig.structComponents = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.structComponents, dataConfig.structComponents.Length + 1);
                        dataConfig.structComponents[dataConfig.structComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                });
            });

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Add Managed Components:");
            GUILayoutExt.Separator();

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.components;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, RegistryComponent>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IComponent>();
                                dataConfig.components[registry.index] = component;
                                this.Save(dataConfig);
                            }
                        }
                        else
                        {
                            var componentName = component.GetType().Name;
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.components[registry.index] = component;
                                    this.Save(dataConfig);
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(18f);
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.components[registry.index] = component;
                                                this.Save(dataConfig);
                                            }
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }

                        GUILayoutExt.DrawComponentHelp(component.GetType());
                        this.DrawComponentTemplatesUsage(dataConfig, component);
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.components.Length; ++i)
                        {
                            if (dataConfig.components[i].GetType() == addType)
                            {
                                var list = dataConfig.components.ToList();
                                list.RemoveAt(i);
                                dataConfig.components = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.components, dataConfig.components.Length + 1);
                        dataConfig.components[dataConfig.components.Length - 1] = (IComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                }, drawRefComponents: true);
            });

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Remove Struct Components:");
            GUILayoutExt.Separator();

            // Remove struct components
            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz         = 0;
                var registries = dataConfig.removeStructComponentsDataTypeIds;
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    var type     = ComponentTypesRegistry.allTypeId.FirstOrDefault(x => x.Value == registry).Key;

                    if (type == null)
                    {
                        continue;
                    }

                    usedComponents.Add(type);

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var componentName   = GUILayoutExt.GetStringCamelCaseSpace(type.Name);

                        EditorGUI.BeginDisabledGroup(true);
                        EditorGUILayout.Toggle(componentName, true);
                        EditorGUI.EndDisabledGroup();

                        GUILayoutExt.DrawComponentHelp(type);
                        this.DrawComponentTemplatesUsage(dataConfig, dataConfig.removeStructComponents[i]);
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.removeStructComponents.Length; ++i)
                        {
                            if (dataConfig.removeStructComponents[i].GetType() == addType)
                            {
                                var list = dataConfig.removeStructComponents.ToList();
                                list.RemoveAt(i);
                                dataConfig.removeStructComponents = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.removeStructComponents, dataConfig.removeStructComponents.Length + 1);
                        dataConfig.removeStructComponents[dataConfig.removeStructComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                });
            });

            if ((dataConfig is ME.ECS.DataConfigs.DataConfigTemplate) == false)
            {
                this.DrawTemplates(dataConfig);
            }
        }
Пример #30
0
    private void OnGUI()
    {
        // font styles
        largeLabelStyle.fontSize      = 14;
        largeLabelStyle.fontStyle     = FontStyle.Bold;
        smallLabelStyle.fontSize      = 12;
        variableLabelStyle.fontSize   = 11;
        variableLabelStyle.fixedWidth = 1;

        bool ableToAddParam = objStrings.Count == 0 ||
                              (objStrings.Count > 0 && objStrings[objStrings.Count - 1] != "Empty");

        EditorGUILayout.LabelField("Evaluation Framework: Objective Value Manager", largeLabelStyle);

        EditorGUILayout.Space();

        scrollPos =
            EditorGUILayout.BeginScrollView(scrollPos);

        EditorGUI.BeginDisabledGroup(!ableToAddParam);
        if (GUILayout.Button(ableToAddParam ? "Add Objective Value" : "Fill Object First"))
        {
            if (objStrings.Count == 0)
            {
                CreateMyAsset();
                objStrings.Add("Empty");
                parameterList.Add(null);
            }
            else if (objStrings[objStrings.Count - 1] != null)
            {
                CreateMyAsset();
                objStrings.Add("Empty");
                parameterList.Add(null);
            }
        }
        EditorGUI.EndDisabledGroup();

        EditorGUILayout.Space();

        for (var i = 0; i < objStrings.Count; i++)
        {
            EditorGUILayout.LabelField(string.Format("{0}. Objective Value", i + 1),
                                       largeLabelStyle);

            if (GUILayout.Button(removeParameter))
            {
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(assets[i]));
                assets.RemoveAt(i);
                objStrings.RemoveAt(i);
                parameterList.RemoveAt(i);
                i--;
                continue;
            }

            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField(objStrings[i], smallLabelStyle);

            EditorGUILayout.Space();
            if (objStrings[i] != "Empty")
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.LabelField("Objective Value Information", largeLabelStyle);

                EditorGUI.indentLevel++;
                EditorGUILayout.LabelField("GameObject: " + parameterList[i].selectedGameObject,
                                           smallLabelStyle);
                EditorGUILayout.LabelField("Component: " + parameterList[i].selectedComponent.GetType(),
                                           smallLabelStyle);
                EditorGUILayout.LabelField("Variable: " + parameterList[i].selectedVariable,
                                           smallLabelStyle);

                EditorGUI.indentLevel = 0;

                EditorGUILayout.Space();
            }
        }

        EditorGUILayout.Space();
        EditorGUILayout.Space();

        if (objStrings.Count != 0 && objStrings[objStrings.Count - 1] != "Empty")
        {
            if (GUILayout.Button(finishedChoosingObjectiveValues))
            {
                objectiveValuesSaved = true;
                CreateObjectiveValueStorage();
                SaveParametersIntoJson();
                GetWindow(typeof(ObjectiveValueManager)).Close();
            }
        }

        EditorGUILayout.EndScrollView();
    }