예제 #1
3
		public override void OnFlowCreateMenuGUI(string prefix, GenericMenu menu) {

			if (this.InstallationNeeded() == false) {

				menu.AddSeparator(prefix);

				menu.AddItem(new GUIContent(prefix + "Social"), on: false, func: () => {

					this.flowEditor.CreateNewItem(() => {

						var window = FlowSystem.CreateWindow(FlowWindow.Flags.IsSmall | FlowWindow.Flags.CantCompiled | FlowWindow.Flags.Tag1);
						window.smallStyleDefault = "flow node 1";
						window.smallStyleSelected = "flow node 1 on";
						window.title = "Social";
						
						window.rect.width = 150f;
						window.rect.height = 100f;

						return window;

					});

				});

			}

		}
예제 #2
0
파일: BundleWnd.cs 프로젝트: tsuixl/Frame
    void OnGUI()
    {
        Rect curWindowRect = EditorGUILayout.BeginVertical();
        {
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
            {
                // Create drop down
                Rect createBtnRect = GUILayoutUtility.GetRect(new GUIContent("Create"), EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false));
                if (GUI.Button(createBtnRect, "Create", EditorStyles.toolbarDropDown))
                {
                    GenericMenu menu = new GenericMenu();
                    menu.DropDown(createBtnRect);
                }


                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Settings", EditorStyles.toolbarButton))
                    BuildSettingEditor.Show();
            }
            EditorGUILayout.EndHorizontal();


        }
        EditorGUILayout.EndVertical();
    }
 private void OnAddDropDown(Rect buttonRect, ReorderableList list)
 {
     var menu = new GenericMenu();
     if (kModule._inputData.Length >= 2) return;
     if (kModule._inputData.Length == 0)
     {
         menu.AddItem(new GUIContent("Right Hand"),
                  false, OnClickHandler,
                  new DataParams() { jointType = KinectUIHandType.Right });
         menu.AddItem(new GUIContent("Left Hand"),
                  false, OnClickHandler,
                  new DataParams() { jointType = KinectUIHandType.Left });
     }
     else if (kModule._inputData.Length == 1)
     {
         DataParams param;
         string name;
         if (kModule._inputData[0].trackingHandType == KinectUIHandType.Left){
             param = new DataParams() { jointType = KinectUIHandType.Right };
             name = "Right Hand";
         }
         else
         {
             param = new DataParams() { jointType = KinectUIHandType.Left };
             name = "Left Hand";
         }
         menu.AddItem(new GUIContent(name),false, OnClickHandler, param);
     }
     menu.ShowAsContext();
 }
    /// <summary>
    /// Create and show a context menu for adding new Timeline Tracks.
    /// </summary>
    protected override void addTrackContext()
    {
        TrackGroup trackGroup = TrackGroup.Behaviour as TrackGroup;
        if(trackGroup != null)
        {
            // Get the possible tracks that this group can contain.
            List<Type> trackTypes = trackGroup.GetAllowedTrackTypes();
            
            GenericMenu createMenu = new GenericMenu();

            // Get the attributes of each track.
            foreach (Type t in trackTypes)
            {
                MemberInfo info = t;
                string label = string.Empty;
                foreach (TimelineTrackAttribute attribute in info.GetCustomAttributes(typeof(TimelineTrackAttribute), true))
                {
                    label = attribute.Label;
                    break;
                }

                createMenu.AddItem(new GUIContent(string.Format("Add {0}", label)), false, addTrack, new TrackContextData(label, t, trackGroup));
            }

            createMenu.ShowAsContext();
        }
    }
 public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
 {
     //SerializedProperty me = prop.FindPropertyRelative("this");
     //SerializedProperty scale = prop.FindPropertyRelative("scale");
     //SerializedProperty curve = prop.FindPropertyRelative("curve");
     //EditorGUI.LabelField(pos, "hi" + resources);
     var rowRect = new Rect(pos.x, pos.y, pos.width, base.GetPropertyHeight(prop, label));
     isFoldedOut = EditorGUI.Foldout(new Rect(rowRect.x, rowRect.y, rowRect.width - 20, rowRect.height), isFoldedOut, "Resources");
     if (isFoldedOut) {
         var resources = prop.FindPropertyRelative("Resources");
         if (GUI.Button(new Rect(rowRect.x + rowRect.width - 22, rowRect.y + 1, 22, rowRect.height - 2), "+")) {
             resources.InsertArrayElementAtIndex(resources.arraySize);
         }
         rowRect.y += rowRect.height;
         for (int i = 0; i < resources.arraySize; ++i) {
             var item = resources.GetArrayElementAtIndex(i);
             var minusClick = GUI.Button(new Rect(rowRect.x, rowRect.y, 22, rowRect.height), "-");
             EditorGUI.PropertyField(new Rect(rowRect.x + 20, rowRect.y, rowRect.width - 21, rowRect.height), item);
             if (minusClick) {
                 if (Event.current.button == 1) {
                     // Now create the menu, add items and show it
                     var menu = new GenericMenu();
                     if (i > 0)
                         menu.AddItem(new GUIContent("Move Up"), false, (itm) => { resources.MoveArrayElement((int)itm, (int)itm - 1); }, i);
                     if (i < resources.arraySize - 1)
                         menu.AddItem(new GUIContent("Move Down"), false, (itm) => { resources.MoveArrayElement((int)itm, (int)itm + 1); }, i);
                     menu.ShowAsContext();
                 } else {
                     resources.DeleteArrayElementAtIndex(i--);
                 }
             }
             rowRect.y += rowRect.height;
         }
     }
 }
예제 #6
0
	private void OnAddEvent(){
		AddTweener (Selection.activeGameObject);
		if (sequence == null) {
			AddSequence (tweener);
		}
		if (sequence.events == null) {
			sequence.events= new List<EventNode>();
		}
		GenericMenu menu = new GenericMenu ();
		//Component[] components=selectedGameObject.GetComponents<Component>();
		List<Type> types = new List<Type> ();
		//types.AddRange (components.Select (x => x.GetType ()));
		types.AddRange (GetSupportedTypes ());
		foreach (Type type in types) {
			List<MethodInfo> functions= GetValidFunctions(type,!(type.IsSubclassOf(typeof(Component)) || type.IsSubclassOf(typeof(MonoBehaviour))) || selectedGameObject.GetComponent(type)==null);
			foreach(MethodInfo mi in functions){
				if(mi != null){
					EventNode node = new EventNode ();
					node.time = timeline.CurrentTime;
					node.SerializedType=type;
					node.method=mi.Name;
					node.arguments=GetMethodArguments(mi);
					menu.AddItem(new GUIContent(type.Name+"/"+mi.Name),false,AddEvent,node);
				}
			}
		}
		menu.ShowAsContext ();
	}
예제 #7
0
		public override GenericMenu GetSettingsMenu(GenericMenu menu) {
			
			if (menu == null) menu = new GenericMenu();
			menu.AddItem(new GUIContent("Reinstall"), false, () => { this.Reinstall(); });
			
			return menu;
			
		}
    protected override void showHeaderContextMenu()
    {
        GenericMenu createMenu = new GenericMenu();
        createMenu.AddItem(new GUIContent("Select"), false, focusActor);
        createMenu.AddItem(new GUIContent("Delete"), false, delete);

        createMenu.ShowAsContext();
    }
    private int controlID; // The control ID for this track control.

    /// <summary>
    /// Header Control 3 is typically the "Add" control.
    /// </summary>
    /// <param name="position">The position that this control is drawn at.</param>
    protected override void updateHeaderControl3(UnityEngine.Rect position)
    {
        TimelineTrack track = TargetTrack.Behaviour as TimelineTrack;
        if (track == null) return;

        Color temp = GUI.color;
        GUI.color = (track.GetTimelineItems().Length > 0) ? Color.green : Color.red;

        controlID = GUIUtility.GetControlID(track.GetInstanceID(), FocusType.Passive, position);

        if (GUI.Button(position, string.Empty, TrackGroupControl.styles.addIcon))
        {
            // Get the possible items that this track can contain.
            List<Type> trackTypes = track.GetAllowedCutsceneItems();

            if (trackTypes.Count == 1)
            {
                // Only one option, so just create it.
                ContextData data = getContextData(trackTypes[0]);
                if (data.PairedType == null)
                {
                    addCutsceneItem(data);
                }
                else
                {
                    showObjectPicker(data);
                }
            }
            else if (trackTypes.Count > 1)
            {
                // Present context menu for selection.
                GenericMenu createMenu = new GenericMenu();
                foreach (Type t in trackTypes)
                {
                    ContextData data = getContextData(t);

                    createMenu.AddItem(new GUIContent(string.Format("{0}/{1}", data.Category, data.Label)), false, addCutsceneItem, data);
                }
                createMenu.ShowAsContext();
            }
        }

        // Handle the case where the object picker has a value selected.
        if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorClosed")
        {
            if (EditorGUIUtility.GetObjectPickerControlID() == controlID)
            {
                UnityEngine.Object pickedObject = EditorGUIUtility.GetObjectPickerObject();

                if(pickedObject != null)
                    addCutsceneItem(savedData, pickedObject);

                Event.current.Use();
            }
        }

        GUI.color = temp;
    }
예제 #10
0
	/// <summary>
	/// Show the context menu with all the added items.
	/// </summary>

	static public void Show ()
	{
		if (mMenu != null)
		{
			mMenu.ShowAsContext();
			mMenu = null;
			mEntries.Clear();
		}
	}
예제 #11
0
	void OpenContextMenu()
	{
		GenericMenu menu = new GenericMenu();

		menu.AddItem (new GUIContent("Open As Floating Window", ""), false, Menu_OpenAsFloatingWindow);
		menu.AddItem (new GUIContent("Open As Dockable Window", ""), false, Menu_OpenAsDockableWindow);

		menu.ShowAsContext ();
	}		
예제 #12
0
    public void ClearConnectionMenu()
    {
        GenericMenu menu = new GenericMenu ();

        menu.AddSeparator ("ARE YOU SURE YOU WANT TO CLEAR?");
        menu.AddSeparator ("");
        menu.AddItem(new GUIContent ("Clear"), false, ClearConnections, "");
        menu.AddItem(new GUIContent ("Don't Clear"), false, DontClearConnections, "");

        menu.ShowAsContext ();
    }
예제 #13
0
    public static void DrawAddTabGUI(List<AlloyTabAdd> tabsToAdd) {
        if (tabsToAdd.Count <= 0) {
            return;
        }
        
        
        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);
        GUILayout.Label("");
        var rect = GUILayoutUtility.GetLastRect();

        rect.x -= 35.0f;
        rect.width += 10.0f;

        GUI.color = Color.clear;
        bool add = GUI.Button(rect, new GUIContent(""), "Box");
        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);
        Rect subRect = rect;

        foreach (var tab in tabsToAdd) {
            GUI.color = tab.Color;
            GUI.Box(subRect, "", "ShurikenModuleTitle");

            subRect.x += rect.width / tabsToAdd.Count;
            subRect.width -= rect.width / tabsToAdd.Count;
        }

        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);

        var delRect = rect;
        delRect.xMin = rect.xMax;
        delRect.xMax += 40.0f;

        if (GUI.Button(delRect, "", "ShurikenModuleTitle") || add) {
            var menu = new GenericMenu();

            foreach (var tab in tabsToAdd) {
                menu.AddItem(new GUIContent(tab.Name), false, tab.Enable);
            }

            menu.ShowAsContext();
        }

        delRect.x += 10.0f;

        GUI.Label(delRect, "+");
        rect.x += EditorGUIUtility.currentViewWidth / 2.0f - 30.0f;

        // Ensures tab text is always white, even when using light skin in pro.
        GUI.color = EditorGUIUtility.isProSkin ? new Color(0.7f, 0.7f, 0.7f) : new Color(0.9f, 0.9f, 0.9f);
        GUI.Label(rect, "Add tab", EditorStyles.whiteLabel);
        GUI.color = Color.white;
    }
	private void OnEnable() {
		list = new ReorderableList(serializedObject, 
		                           serializedObject.FindProperty("Waves"), 
		                           true, true, true, true);
		list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
			var element = list.serializedProperty.GetArrayElementAtIndex(index);
			rect.y += 2;
			EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Type"), GUIContent.none);
			EditorGUI.PropertyField(new Rect(rect.x + 60, rect.y, rect.width - 60 - 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Prefab"), GUIContent.none);
			EditorGUI.PropertyField(new Rect(rect.x + rect.width - 30, rect.y, 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Count"), GUIContent.none);
		};
		list.drawHeaderCallback = (Rect rect) => {
			EditorGUI.LabelField(rect, "Monster Waves");
		};
		list.onSelectCallback = (ReorderableList l) => {
			var prefab = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("Prefab").objectReferenceValue as GameObject;
			if (prefab) EditorGUIUtility.PingObject(prefab.gameObject);
		};
		list.onCanRemoveCallback = (ReorderableList l) => {
			return l.count > 1;
		};
		list.onRemoveCallback = (ReorderableList l) => {
			if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete the wave?", "Yes", "No"))
			{
				ReorderableList.defaultBehaviours.DoRemoveButton(l);
			}
		};
		list.onAddCallback = (ReorderableList l) => {
			var index = l.serializedProperty.arraySize;
			l.serializedProperty.arraySize++;
			l.index = index;
			var element = l.serializedProperty.GetArrayElementAtIndex(index);
			element.FindPropertyRelative("Type").enumValueIndex = 0;
			element.FindPropertyRelative("Count").intValue = 20;
			element.FindPropertyRelative("Prefab").objectReferenceValue = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Mobs/Cube.prefab", typeof(GameObject)) as GameObject;
		};
		list.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => {
			var menu = new GenericMenu();
			var guids = AssetDatabase.FindAssets("", new[]{"Assets/Prefabs/Mobs"});
			foreach (var guid in guids) {
				var path = AssetDatabase.GUIDToAssetPath(guid);
				menu.AddItem(new GUIContent("Mobs/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams() {Type = MobWave.WaveType.Mobs, Path = path});
			}
			guids = AssetDatabase.FindAssets("", new[]{"Assets/Prefabs/Bosses"});
			foreach (var guid in guids) {
				var path = AssetDatabase.GUIDToAssetPath(guid);
				menu.AddItem(new GUIContent("Bosses/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams() {Type = MobWave.WaveType.Boss, Path = path});
			}
			menu.ShowAsContext();
		};
	}
예제 #15
0
 void OnGUI()
 {
     windowRect = new Rect(0, 0, Screen.width, Screen.height);
     if(Event.current.type == EventType.ContextClick)
     {
         Vector2 mousePos = Event.current.mousePosition;
         if(windowRect.Contains(mousePos))
         {
             GenericMenu menu = new GenericMenu();
             menu.AddItem(new GUIContent("CreateCube"), false, createMenu, "createCube");
             menu.ShowAsContext();
         }
     }
 }
예제 #16
0
	void Selector(SerializedProperty property) {
		SpineSlot attrib = (SpineSlot)attribute;
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
		if (data == null)
			return;

		GenericMenu menu = new GenericMenu();

		menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		for (int i = 0; i < data.Slots.Count; i++) {
			string name = data.Slots.Items[i].Name;
			if (name.StartsWith(attrib.startsWith)) {
				if (attrib.containsBoundingBoxes) {

					int slotIndex = i;

					List<Attachment> attachments = new List<Attachment>();
					foreach (var skin in data.Skins) {
						skin.FindAttachmentsForSlot(slotIndex, attachments);
					}

					bool hasBoundingBox = false;
					foreach (var attachment in attachments) {
						if (attachment is BoundingBoxAttachment) {
							menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
							hasBoundingBox = true;
							break;
						}
					}

					if (!hasBoundingBox)
						menu.AddDisabledItem(new GUIContent(name));
					

				} else {
					menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
				}
				
			}
				
		}

		menu.ShowAsContext();
	}
예제 #17
0
    public static void CreateNodeMenu(Vector2 position, GenericMenu.MenuFunction2 MenuCallback)
    {
        GenericMenu menu = new GenericMenu();

        var assembly = Assembly.Load(new AssemblyName("Assembly-CSharp"));
        var paramTypes = (from t in assembly.GetTypes() where t.IsSubclassOfRawGeneric(typeof(AParameterNode<>)) && !t.IsAbstract select t).ToArray();
        var flowTypes = (from t in assembly.GetTypes() where t.IsSubclassOfRawGeneric(typeof(AFlowNode)) && !t.IsAbstract select t).ToArray();
        foreach(System.Type t in paramTypes) {
            menu.AddItem(new GUIContent(string.Format("Parameter Nodes/{0}", t.Name)), false, MenuCallback, new NodeCallbackData(position, t));
        }
        foreach(System.Type t in flowTypes) {
            menu.AddItem(new GUIContent(string.Format("Flow Nodes/{0}", t.Name)), false, MenuCallback, new NodeCallbackData(position, t));
        }
        menu.AddItem(new GUIContent("TaskNode"), false, MenuCallback, new NodeCallbackData(position, typeof(TaskNode)));
        menu.AddItem(new GUIContent("TreeNode"), false, MenuCallback, new NodeCallbackData(position, typeof(TreeNode)));
        menu.ShowAsContext();
    }
 private void ShowAddTriggermenu()
 {
   GenericMenu genericMenu = new GenericMenu();
   for (int index1 = 0; index1 < this.m_EventTypes.Length; ++index1)
   {
     bool flag = true;
     for (int index2 = 0; index2 < this.m_DelegatesProperty.arraySize; ++index2)
     {
       if (this.m_DelegatesProperty.GetArrayElementAtIndex(index2).FindPropertyRelative("eventID").enumValueIndex == index1)
         flag = false;
     }
     if (flag)
       genericMenu.AddItem(this.m_EventTypes[index1], false, new GenericMenu.MenuFunction2(this.OnAddNewSelected), (object) index1);
     else
       genericMenu.AddDisabledItem(this.m_EventTypes[index1]);
   }
   genericMenu.ShowAsContext();
   Event.current.Use();
 }
예제 #19
0
	/// <summary>
	/// Add a new context menu entry.
	/// </summary>

	static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
	{
		if (callback != null)
		{
			if (mMenu == null) mMenu = new GenericMenu();
			int count = 0;

			for (int i = 0; i < mEntries.size; ++i)
			{
				string str = mEntries[i];
				if (str == item) ++count;
			}
			mEntries.Add(item);

			if (count > 0) item += " [" + count + "]";
			mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
		}
		else AddDisabledItem(item);
	}
    protected override void showBodyContextMenu(Event evt)
    {
        MultiCurveTrack itemTrack = TargetTrack.Behaviour as MultiCurveTrack;
        if (itemTrack == null) return;

        Behaviour b = DirectorCopyPaste.Peek();

        PasteContext pasteContext = new PasteContext(evt.mousePosition, itemTrack);
        GenericMenu createMenu = new GenericMenu();
        if (b != null && DirectorHelper.IsTrackItemValidForTrack(b, itemTrack))
        {
            createMenu.AddItem(new GUIContent("Paste"), false, pasteItem, pasteContext);
        }
        else
        {
            createMenu.AddDisabledItem(new GUIContent("Paste"));
        }
        createMenu.ShowAsContext();
    }
    private void BuildMenu(GenericMenu menu, Type type, string itemVisiblePath, string itemInternalPath, bool addSelf, int depth, GenericMenu.MenuFunction2 function)
    {
        if (addSelf) {
            menu.AddItem (new GUIContent (itemVisiblePath + "/" + type.Name), false, function, itemInternalPath);
        }
        var members = UTComponentScanner.FindPublicWritableMembersOf (type);
        foreach (var memberInfo in members.MemberInfos) {

            var newInternalPath = string.IsNullOrEmpty (itemInternalPath) ? memberInfo.Name : itemInternalPath + "." + memberInfo.Name;
            var newVisiblePath = string.IsNullOrEmpty (itemVisiblePath) ? memberInfo.Name : itemVisiblePath + "/" + memberInfo.Name;
            if (memberInfo.DeclaringType != typeof(Component)) {
                    var memberInfoType = UTInternalCall.GetMemberType (memberInfo);
                    if (UTInternalCall.HasMembers (memberInfoType) && depth < 2) {
                        BuildMenu (menu, memberInfoType, newVisiblePath, newInternalPath, UTInternalCall.IsWritable (memberInfo), depth + 1, function);
                    } else {
                        menu.AddItem (new GUIContent (newVisiblePath), false, function, newInternalPath);
                    }
            }
        }
    }
    protected override void showContextMenu(Behaviour behaviour)
    {
        CinemaActorClipCurve clipCurve = behaviour as CinemaActorClipCurve;
        if (clipCurve == null) return;

        List<KeyValuePair<string, string>> currentCurves = new List<KeyValuePair<string, string>>();
        foreach (MemberClipCurveData data in clipCurve.CurveData)
        {
            KeyValuePair<string, string> curveStrings = new KeyValuePair<string, string>(data.Type, data.PropertyName);
            currentCurves.Add(curveStrings);
        }

        GenericMenu createMenu = new GenericMenu();

        if (clipCurve.Actor != null)
        {
            Component[] components = DirectorHelper.getValidComponents(clipCurve.Actor.gameObject);

            for (int i = 0; i < components.Length; i++)
            {
                Component component = components[i];
                MemberInfo[] members = DirectorHelper.getValidMembers(component);
                for (int j = 0; j < members.Length; j++)
                {
                    AddCurveContext context = new AddCurveContext();
                    context.clipCurve = clipCurve;
                    context.component = component;
                    context.memberInfo = members[j];
                    if (!currentCurves.Contains(new KeyValuePair<string, string>(component.GetType().Name, members[j].Name)))
                    {
                        createMenu.AddItem(new GUIContent(string.Format("Add Curve/{0}/{1}", component.GetType().Name, DirectorHelper.GetUserFriendlyName(component, members[j]))), false, addCurve, context);
                    }
                }
            }
            createMenu.AddSeparator(string.Empty);
        }
        createMenu.AddItem(new GUIContent("Copy"), false, copyItem, behaviour);
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Clear"), false, deleteItem, clipCurve);
        createMenu.ShowAsContext();
    }
		public override GenericMenu GetSettingsMenu(GenericMenu menu) {

			if (menu == null) menu = new GenericMenu();
			menu.AddItem(new GUIContent("Setup"), false, () => {
				
				if (EditorUtility.DisplayDialog("Warning!",
				                                "You want to setup all audio in your screens. It may causes some problems with id's. Do you want to continue?",
				                                "Yes, go ahead",
				                                "No") == true) {
					
					var data = FlowSystem.GetData();
					if (data == null) return;

					data.audio.Setup();
					
				}
				
			});

			return menu;

		}
    protected override void showContextMenu(Behaviour behaviour)
    {
        CinemaShot shot = behaviour as CinemaShot;
        if (shot == null) return;

        Camera[] cameras = GameObject.FindObjectsOfType<Camera>();
        
        GenericMenu createMenu = new GenericMenu();
        createMenu.AddItem(new GUIContent("Focus"), false, focusShot, shot);
        foreach (Camera c in cameras)
        {
            
            ContextSetCamera arg = new ContextSetCamera();
            arg.shot = shot;
            arg.camera = c;
            createMenu.AddItem(new GUIContent(string.Format(MODIFY_CAMERA, c.gameObject.name)), false, setCamera, arg);
        }
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Copy"), false, copyItem, behaviour);
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Clear"), false, deleteItem, shot);
        createMenu.ShowAsContext();
    }
예제 #25
0
	private void ShowAddEventmenu(){
		GenericMenu genericMenu = new GenericMenu();
		for (int i = 0; i < (int)this.eventCallbackTypes.Length; i++)
		{
			bool flag = true;
			for (int j = 0; j < this.delegatesProperty.arraySize; j++)
			{
				if (this.delegatesProperty.GetArrayElementAtIndex(j).FindPropertyRelative("eventID").stringValue == eventCallbackTypes[i].text)
				{
					flag = false;
				}
			}
			if (!flag)
			{
				genericMenu.AddDisabledItem(this.eventCallbackTypes[i]);
			}
			else
			{
				genericMenu.AddItem(this.eventCallbackTypes[i], false, new GenericMenu.MenuFunction2(this.OnAddNewSelected), eventCallbackTypes[i].text);
			}
		}
		genericMenu.ShowAsContext();
		Event.current.Use();
	}
예제 #26
0
        public static ReorderableList CreateTileViewReorderableList(Tileset tileset)
        {
            ReorderableList tileViewRList = new ReorderableList(tileset.TileViews, typeof(TileView), true, true, true, true);

            tileViewRList.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) =>
            {
                GenericMenu menu = new GenericMenu();
                GenericMenu.MenuFunction addTileSelectionFunc = () =>
                {
                    TileSelection tileSelection = tileset.TileSelection.Clone();
                    tileSelection.FlipVertical(); // flip vertical to fit the tileset coordinate system ( from top to bottom )
                    tileset.AddTileView("new TileView", tileSelection);
                    EditorUtility.SetDirty(tileset);
                };
                GenericMenu.MenuFunction addBrushSelectionFunc = () =>
                {
                    TileSelection tileSelection = BrushBehaviour.CreateTileSelection();
                    tileset.AddTileView("new TileView", tileSelection);
                    EditorUtility.SetDirty(tileset);
                };
                GenericMenu.MenuFunction removeAllTileViewsFunc = () =>
                {
                    if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete all the TileViews?", "Yes", "No"))
                    {
                        tileset.RemoveAllTileViews();
                        EditorUtility.SetDirty(tileset);
                    }
                };
                if (tileset.TileSelection != null)
                {
                    menu.AddItem(new GUIContent("Add Tile Selection"), false, addTileSelectionFunc);
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Add Tile Selection to TileView"));
                }

                if (BrushBehaviour.GetBrushTileset() == tileset && BrushBehaviour.CreateTileSelection() != null)
                {
                    menu.AddItem(new GUIContent("Add Brush Selection"), false, addBrushSelectionFunc);
                }

                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Remove All TileViews"), false, removeAllTileViewsFunc);
                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Sort By Name"), false, tileset.SortTileViewsByName);
                menu.ShowAsContext();
            };
            tileViewRList.onRemoveCallback = (ReorderableList list) =>
            {
                if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete the TileView?", "Yes", "No"))
                {
                    ReorderableList.defaultBehaviours.DoRemoveButton(list);
                    EditorUtility.SetDirty(tileset);
                }
            };
            tileViewRList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "TileViews", EditorStyles.boldLabel);
                Texture2D btnTexture = tileViewRList.elementHeight == 0f ? EditorGUIUtility.FindTexture("winbtn_win_max_h") : EditorGUIUtility.FindTexture("winbtn_win_min_h");
                if (GUI.Button(new Rect(rect.width - rect.height, rect.y, rect.height, rect.height), btnTexture, EditorStyles.label))
                {
                    tileViewRList.elementHeight = tileViewRList.elementHeight == 0f ? EditorGUIUtility.singleLineHeight : 0f;
                    tileViewRList.draggable     = tileViewRList.elementHeight > 0f;
                }
            };
            tileViewRList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                if (tileViewRList.elementHeight == 0f)
                {
                    return;
                }
                Rect     rLabel   = new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight);
                TileView tileView = tileViewRList.list[index] as TileView;
                if (index == tileViewRList.index)
                {
                    string newName = EditorGUI.TextField(rLabel, tileView.name);
                    if (newName != tileView.name)
                    {
                        tileset.RenameTileView(tileView.name, newName);
                    }
                }
                else
                {
                    EditorGUI.LabelField(rLabel, tileView.name);
                }
            };

            return(tileViewRList);
        }
예제 #27
0
    //CONTEXT MENU

    static void AddMenuItem(GenericMenu menu, string menuPath, Transform asset) //ADD ITEM TO MENU
    {
        menu.AddItem(new GUIContent(menuPath), false, OnItemSelected, asset);
    }
        private GenericMenu ElementContextMenu(IList list, int index)
        {
            GenericMenu menu = new GenericMenu();

            if (list[index] == null)
            {
                return(menu);
            }
            menu.AddItem(new GUIContent("Reset"), false, delegate {
                object value = System.Activator.CreateInstance(list[index].GetType());
                list[index]  = value;
            });
            menu.AddSeparator(string.Empty);
            menu.AddItem(new GUIContent("Remove " + this.m_ElementType.Name), false, delegate { list.RemoveAt(index); EditorUtility.SetDirty(target); });

            if (index > 0)
            {
                menu.AddItem(new GUIContent("Move Up"), false, delegate {
                    object value = list[index];
                    list.RemoveAt(index);
                    list.Insert(index - 1, value);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Up"));
            }

            if (index < list.Count - 1)
            {
                menu.AddItem(new GUIContent("Move Down"), false, delegate
                {
                    object value = list[index];
                    list.RemoveAt(index);
                    list.Insert(index + 1, value);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Down"));
            }

            menu.AddItem(new GUIContent("Copy " + this.m_ElementType.Name), false, delegate {
                object value   = list[index];
                m_ObjectToCopy = value;
            });

            if (m_ObjectToCopy != null)
            {
                menu.AddItem(new GUIContent("Paste " + this.m_ElementType.Name + " As New"), false, delegate {
                    object instance    = System.Activator.CreateInstance(m_ObjectToCopy.GetType());
                    FieldInfo[] fields = instance.GetType().GetSerializedFields();
                    for (int i = 0; i < fields.Length; i++)
                    {
                        object value = fields[i].GetValue(m_ObjectToCopy);
                        fields[i].SetValue(instance, value);
                    }
                    list.Insert(index + 1, instance);
                });

                if (list[index].GetType() == m_ObjectToCopy.GetType())
                {
                    menu.AddItem(new GUIContent("Paste " + this.m_ElementType.Name + " Values"), false, delegate
                    {
                        object instance    = list[index];
                        FieldInfo[] fields = instance.GetType().GetSerializedFields();
                        for (int i = 0; i < fields.Length; i++)
                        {
                            object value = fields[i].GetValue(m_ObjectToCopy);
                            fields[i].SetValue(instance, value);
                        }
                    });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Paste " + this.m_ElementType.Name + " Values"));
                }
            }

            if (list[index] != null)
            {
                MonoScript script = EditorTools.FindMonoScript(list[index].GetType());
                if (script != null)
                {
                    menu.AddSeparator(string.Empty);
                    menu.AddItem(new GUIContent("Edit Script"), false, delegate { AssetDatabase.OpenAsset(script); });
                }
            }
            return(menu);
        }
 /// <summary>
 /// You can implement this method to add custom menut items to the context menu for this Timeline as such.
 ///
 /// contextMenu.AddItem(new GUIContent("My Context Item/My Sub Context Menu Item"), false, MyDelegate, null);
 ///
 /// More information can be found at Unity's official page : https://docs.unity3d.com/353/Documentation/ScriptReference/GenericMenu.html
 ///
 /// </summary>
 /// <param name="contextMenu">The contextMenu that will be executed.</param>
 public virtual void AddContextItems(GenericMenu contextMenu)
 {
     ;
 }
예제 #30
0
    void OnGUI()
    {
        GUIStyle boldNumberFieldStyle = new GUIStyle(EditorStyles.numberField);

        boldNumberFieldStyle.font = EditorStyles.boldFont;

        GUIStyle boldToggleStyle = new GUIStyle(EditorStyles.toggle);

        boldToggleStyle.font = EditorStyles.boldFont;

        GUI.enabled = !waitTillPlistHasBeenWritten;

        //Toolbar
        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
        {
            Rect optionsRect = GUILayoutUtility.GetRect(0, 20, GUILayout.ExpandWidth(false));

            if (GUILayout.Button(new GUIContent("Sort   " + (sortAscending ? "▼" : "▲"), "Change sorting to " + (sortAscending ? "descending" : "ascending")), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                OnChangeSortModeClicked();
            }

            if (GUILayout.Button(new GUIContent("Options", "Contains additional functionality like \"Add new entry\" and \"Delete all entries\" "), EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false)))
            {
                GenericMenu options = new GenericMenu();
                options.AddItem(new GUIContent("New Entry..."), false, OnNewEntryClicked);
                options.AddSeparator("");
                options.AddItem(new GUIContent("Delete Selected Entries"), false, OnDeleteSelectedClicked);
                options.AddItem(new GUIContent("Delete All Entries"), false, OnDeleteAllClicked);
                options.DropDown(optionsRect);
            }

            GUILayout.FlexibleSpace();

            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                string refreshTooltip = "Should all entries be automaticly refreshed every " + UpdateIntervalInSeconds + " seconds?";
                autoRefresh = GUILayout.Toggle(autoRefresh, new GUIContent("Auto Refresh ", refreshTooltip), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false), GUILayout.MinWidth(20));
            }

            if (GUILayout.Button(new GUIContent(RefreshIcon, "Force a refresh, could take a few seconds."), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)))
            {
                RefreshKeys();
            }

            Rect r;
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                r = GUILayoutUtility.GetRect(16, 16);
            }
            else
            {
                r = GUILayoutUtility.GetRect(9, 16);
            }

            if (waitTillPlistHasBeenWritten)
            {
                Texture2D t = AssetDatabase.LoadAssetAtPath(IconsPath + "loader/" + (Mathf.FloorToInt(rotation % 12) + 1) + ".png", typeof(Texture2D)) as Texture2D;

                GUI.DrawTexture(new Rect(r.x + 3, r.y, 16, 16), t);
            }
        }
        EditorGUILayout.EndHorizontal();

        GUI.enabled = !waitTillPlistHasBeenWritten;

        if (showNewEntryBox)
        {
            GUILayout.BeginHorizontal(GUI.skin.box);
            {
                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));
                {
                    newKey = EditorGUILayout.TextField("Key", newKey);
                    switch (selectedType)
                    {
                    default:
                    case ValueType.String:
                        newValueString = EditorGUILayout.TextField("Value", newValueString);
                        break;

                    case ValueType.Float:
                        newValueFloat = EditorGUILayout.FloatField("Value", newValueFloat);
                        break;

                    case ValueType.Int:
                        newValueInt = EditorGUILayout.IntField("Value", newValueInt);
                        break;
                    }

                    selectedType = (ValueType)EditorGUILayout.EnumPopup("Type", selectedType);
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.Width(1));
                {
                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.FlexibleSpace();

                        if (GUILayout.Button(new GUIContent("X", "Close"), EditorStyles.boldLabel, GUILayout.ExpandWidth(false)))
                        {
                            showNewEntryBox = false;
                        }
                    }
                    GUILayout.EndHorizontal();

                    if (GUILayout.Button(new GUIContent(AddIcon, "Add a new key-value.")))
                    {
                        if (!string.IsNullOrEmpty(newKey))
                        {
                            switch (selectedType)
                            {
                            case ValueType.Int:
                                PlayerPrefs.SetInt(newKey, newValueInt);
                                ppeList.Add(new PlayerPrefsEntry(newKey, newValueInt));
                                break;

                            case ValueType.Float:
                                PlayerPrefs.SetFloat(newKey, newValueFloat);
                                ppeList.Add(new PlayerPrefsEntry(newKey, newValueFloat));
                                break;

                            default:
                            case ValueType.String:
                                PlayerPrefs.SetString(newKey, newValueString);
                                ppeList.Add(new PlayerPrefsEntry(newKey, newValueString));
                                break;
                            }
                            PlayerPrefs.Save();
                        }

                        newKey        = newValueString = "";
                        newValueInt   = 0;
                        newValueFloat = 0;
                        GUIUtility.keyboardControl = 0; //move focus from textfield, else the text won't be cleared
                        showNewEntryBox            = false;
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();
        }

        GUILayout.Space(2);


        GUI.backgroundColor = Color.white;
        EditorGUI.indentLevel++;
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
        {
            EditorGUILayout.BeginVertical();
            {
                for (int i = 0; i < ppeList.Count; i++)
                {
                    if (ppeList[i].Value != null)
                    {
                        EditorGUILayout.BeginHorizontal();
                        {
                            ppeList[i].IsSelected = GUILayout.Toggle(ppeList[i].IsSelected, new GUIContent(ppeList[i].Key, "Toggle selection."), ppeList[i].HasChanged ? boldToggleStyle : EditorStyles.toggle, GUILayout.MinWidth(40), GUILayout.MaxWidth(125), GUILayout.ExpandWidth(true));

                            GUIStyle numberFieldStyle = ppeList[i].HasChanged ? boldNumberFieldStyle : EditorStyles.numberField;

                            switch (ppeList[i].Type)
                            {
                            default:
                            case ValueType.String:
                                ppeList[i].Value = EditorGUILayout.TextField("", (string)ppeList[i].Value, numberFieldStyle, GUILayout.MinWidth(40));
                                break;

                            case ValueType.Float:
                                ppeList[i].Value = EditorGUILayout.FloatField("", (float)ppeList[i].Value, numberFieldStyle, GUILayout.MinWidth(40));
                                break;

                            case ValueType.Int:
                                ppeList[i].Value = EditorGUILayout.IntField("", (int)ppeList[i].Value, numberFieldStyle, GUILayout.MinWidth(40));
                                break;
                            }

                            GUI.enabled = ppeList[i].HasChanged && !waitTillPlistHasBeenWritten;
                            if (GUILayout.Button(new GUIContent(SaveIcon, "Save changes made to this value."), GUILayout.ExpandWidth(false)))
                            {
                                ppeList[i].SaveChanges();
                            }

                            if (GUILayout.Button(new GUIContent(UndoIcon, "Discard changes made to this value."), GUILayout.ExpandWidth(false)))
                            {
                                ppeList[i].RevertChanges();
                            }

                            GUI.enabled = !waitTillPlistHasBeenWritten;

                            if (GUILayout.Button(new GUIContent(DeleteIcon, "Delete this key-value."), GUILayout.ExpandWidth(false)))
                            {
                                PlayerPrefs.DeleteKey(ppeList[i].Key);
                                ppeList.Remove(ppeList[i]);
                                PlayerPrefs.Save();
                                break;
                            }
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }
            }
            EditorGUILayout.EndVertical();
        }
        EditorGUILayout.EndScrollView();
        EditorGUI.indentLevel--;
    }
예제 #31
0
 public void AddItemsToMenu(GenericMenu menu)
 {
     menu.AddItem(new GUIContent("Lock"), false, () => { isLock = !isLock; });
 }
예제 #32
0
    public override void OnInspectorGUI()
    {
        DrawToolbarGUI();

        bool dirty = DrawGeneralGUI();

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showMarkers = Foldout(showMarkers, "2D Markers");
        if (showMarkers) DrawMarkersGUI();
        EditorGUILayout.EndVertical();

        if (api.target == OnlineMapsTarget.texture)
        {
            EditorGUILayout.BeginVertical(GUI.skin.box);
            showCreateTexture = Foldout(showCreateTexture, "Create texture");
            if (showCreateTexture) DrawCreateTextureGUI(ref dirty);
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showAdvanced = Foldout(showAdvanced, "Advanced");
        if (showAdvanced) DrawAdvancedGUI(ref dirty);
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showTroubleshooting = Foldout(showTroubleshooting, "Troubleshooting");
        if (showTroubleshooting) DrawTroubleshootingGUI(ref dirty);
        EditorGUILayout.EndVertical();

        OnlineMapsControlBase[] controls = api.GetComponents<OnlineMapsControlBase>();
        if (controls == null || controls.Length == 0)
        {
            EditorGUILayout.BeginVertical(GUI.skin.box);

            EditorGUILayout.HelpBox("Problem detected:\nCan not find OnlineMaps Control component.", MessageType.Error);
            if (GUILayout.Button("Add Control"))
            {
                GenericMenu menu = new GenericMenu();

                Type[] types = api.GetType().Assembly.GetTypes();
                foreach (Type t in types)
                {
                    if (t.IsSubclassOf(typeof(OnlineMapsControlBase)))
                    {
                        if (t == typeof(OnlineMapsControlBase2D) || t == typeof(OnlineMapsControlBase3D)) continue;

                        string fullName = t.FullName.Substring(10);

                        int controlIndex = fullName.IndexOf("Control");
                        fullName = fullName.Insert(controlIndex, " ");

                        int textureIndex = fullName.IndexOf("Texture");
                        if (textureIndex > 0) fullName = fullName.Insert(textureIndex, " ");

                        menu.AddItem(new GUIContent(fullName), false, data =>
                        {
                            Type ct = data as Type;
                            api.gameObject.AddComponent(ct);
                            api.target = (ct == typeof (OnlineMapsTileSetControl))
                                ? OnlineMapsTarget.tileset
                                : OnlineMapsTarget.texture;
                            Repaint();
                        }, t);
                    }
                }

                menu.ShowAsContext();
            }

            EditorGUILayout.EndVertical();
        }

        if (dirty)
        {
            EditorUtility.SetDirty(api);
            Repaint();
        }
    }
예제 #33
0
        private void DrawLODLevelSlider(Rect sliderPosition, List <LODGUI.LODInfo> lods)
        {
            int   sliderId = GUIUtility.GetControlID(m_LODSliderId, FocusType.Passive);
            int   camerId  = GUIUtility.GetControlID(m_CameraSliderId, FocusType.Passive);
            Event evt      = Event.current;

            switch (evt.GetTypeForControl(sliderId))
            {
            case EventType.Repaint:
            {
                LODGUI.DrawLODSlider(sliderPosition, lods, SelectedLOD);
                break;
            }

            case EventType.MouseDown:
            {
                if (evt.button == 1 && sliderPosition.Contains(evt.mousePosition))         // right click
                {
                    float cameraPercent = LODGUI.GetCameraPercent(evt.mousePosition, sliderPosition);
                    var   pm            = new GenericMenu();
                    if (lods.Count >= 8)
                    {
                        pm.AddDisabledItem(EditorGUIUtility.TrTextContent("Insert Before"));
                    }
                    else
                    {
                        pm.AddItem(EditorGUIUtility.TrTextContent("Insert Before"), false,
                                   new LODAction(lods, cameraPercent, evt.mousePosition, m_LODs, InsertLod).InsertLOD);
                    }

                    // culled region
                    bool disabledRegion = !(lods.Count > 0 && lods[lods.Count - 1].RawScreenPercent < cameraPercent);

                    if (disabledRegion)
                    {
                        pm.AddDisabledItem(EditorGUIUtility.TrTextContent("Delete"));
                    }
                    else
                    {
                        pm.AddItem(EditorGUIUtility.TrTextContent("Delete"), false,
                                   new LODAction(lods, cameraPercent, evt.mousePosition, m_LODs, DeletedLOD).DeleteLOD);
                    }
                    pm.ShowAsContext();

                    bool selected = false;
                    foreach (var lod in lods)
                    {
                        if (lod.m_RangePosition.Contains(evt.mousePosition))
                        {
                            SelectedLOD = lod.LODLevel;
                            selected    = true;
                            break;
                        }
                    }
                    if (!selected)
                    {
                        SelectedLOD = -1;
                    }
                    evt.Use();
                    break;
                }

                // edge buttons overflow by 5 pixels
                var barPosition = sliderPosition;
                barPosition.x     -= 5;
                barPosition.width += 10;

                if (barPosition.Contains(evt.mousePosition))
                {
                    evt.Use();
                    GUIUtility.hotControl = sliderId;
                    bool clickedButton = false;
                    lods.OrderByDescending(x => x.LODLevel);
                    foreach (var lod in lods)
                    {
                        if (lod.m_ButtonPosition.Contains(evt.mousePosition))
                        {
                            m_SelectedLODSlider = lod.LODLevel;
                            clickedButton       = true;
                            m_cameraPercent     = lod.RawScreenPercent + 0.001f;
                            // Bias by 0.1% so that there is no skipping when sliding
                            BeginLODDrag();
                            break;
                        }
                    }
                    if (!clickedButton)
                    {
                        foreach (var lod in lods)
                        {
                            if (lod.m_RangePosition.Contains(evt.mousePosition))
                            {
                                m_SelectedLODSlider = -1;
                                SelectedLOD         = lod.LODLevel;
                                break;
                            }
                        }
                    }
                }
                break;
            }

            case EventType.MouseDrag:
            {
                if (GUIUtility.hotControl == sliderId && m_SelectedLODSlider >= 0 && lods[m_SelectedLODSlider] != null)
                {
                    evt.Use();
                    var cameraPercent = LODGUI.GetCameraPercent(evt.mousePosition, sliderPosition);
                    // Bias by 0.1% so that there is no skipping when sliding
                    LODGUI.SetSelectedLODLevelPercentage(cameraPercent - 0.001f, m_SelectedLODSlider, lods);
                    m_LODs[m_SelectedLODSlider].screenPercentage = cameraPercent;
                    UpdateLODDrag();
                }
                break;
            }

            case EventType.MouseUp:
            {
                if (GUIUtility.hotControl == sliderId)
                {
                    GUIUtility.hotControl = 0;
                    m_SelectedLODSlider   = -1;
                    EndLODDrag();
                    evt.Use();
                }
                break;
            }

            case EventType.DragUpdated:
            case EventType.DragPerform:
            {
                var lodLevel = -2;
                foreach (var lod in lods)
                {
                    if (lod.m_RangePosition.Contains(evt.mousePosition))
                    {
                        lodLevel = lod.LODLevel;
                        break;
                    }
                }
                if (lodLevel >= 0)
                {
                    SelectedLOD            = lodLevel;
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (DragAndDrop.objectReferences.Count() > 0)
                    {
                        if (evt.type == EventType.DragPerform)
                        {
                            var selectedGameObjects = from go in DragAndDrop.objectReferences
                                                      where go as GameObject != null
                                                      select go as GameObject;
                            if (selectedGameObjects.Count() > 0)
                            {
                                var go = selectedGameObjects.First();
                                if (go != null)
                                {
                                    m_LODs[SelectedLOD].Drop(go);
                                    UpdateBehavic();
                                    OnLodChanged(m_selectLOD);
                                    Debug.Log("drop lod: " + SelectedLOD + " " + go.name);
                                }
                            }
                            DragAndDrop.AcceptDrag();
                        }
                        evt.Use();
                    }
                }
                break;
            }

            case EventType.DragExited:
            {
                evt.Use();
                break;
            }
            }

            var cameraRect        = LODGUI.CalcLODButton(sliderPosition, LODGUI.DelinearizeScreenPercentage(m_cameraPercent));
            var cameraIconRect    = new Rect(cameraRect.center.x - 15, cameraRect.y - 25, 32, 32);
            var cameraLineRect    = new Rect(cameraRect.center.x - 1, cameraRect.y, 2, cameraRect.height);
            var cameraPercentRect = new Rect(cameraIconRect.center.x - 5, cameraLineRect.yMax, 35, 20);

            switch (evt.GetTypeForControl(camerId))
            {
            case EventType.Repaint:
            {
                var colorCache = GUI.backgroundColor;
                GUI.backgroundColor = new Color(colorCache.r, colorCache.g, colorCache.b, 0.8f);
                LODGUI.Styles.LODCameraLine.Draw(cameraLineRect, false, false, false, false);
                GUI.backgroundColor = colorCache;
                GUI.Label(cameraIconRect, LODGUI.Styles.CameraIcon, GUIStyle.none);
                LODGUI.Styles.LODSliderText.Draw(cameraPercentRect, String.Format("{0:0}%", Mathf.Clamp01(m_cameraPercent) * 100.0f), false, false, false, false);
                break;
            }

            case EventType.MouseDown:
            {
                if (cameraIconRect.Contains(evt.mousePosition))
                {
                    evt.Use();
                    var cameraPercent = LODGUI.GetCameraPercent(evt.mousePosition, sliderPosition);

                    UpdateSelectedLODFromCamera(lods, cameraPercent);
                    GUIUtility.hotControl = camerId;
                    BeginLODDrag();
                }
                break;
            }

            case EventType.MouseDrag:
            {
                if (GUIUtility.hotControl == camerId)
                {
                    evt.Use();
                    m_cameraPercent = LODGUI.GetCameraPercent(evt.mousePosition, sliderPosition);
                    UpdateSelectedLODFromCamera(lods, m_cameraPercent);
                    UpdateLODDrag();
                }
                break;
            }

            case EventType.MouseUp:
            {
                if (GUIUtility.hotControl == camerId)
                {
                    EndLODDrag();
                    GUIUtility.hotControl = 0;
                    evt.Use();
                }
                break;
            }
            }
        }
예제 #34
0
    private void Draw()
    {
        bool inRect = DrawGroup (position, menuItems);

        while (groupToDraw != null && activeMenu != null)
        {
            MenuItem group = groupToDraw;
            groupToDraw = null;
            if (group.group)
            {
                if (DrawGroup (group.groupPos, group.subItems))
                    inRect = true;
            }
        }

        if (!inRect)
            activeMenu = null;

        if (NodeEditorFramework.NodeEditor.Repaint != null)
            NodeEditorFramework.NodeEditor.Repaint ();
    }
        void InitializeCustomPostProcessesLists()
        {
            var ppVolumeTypeInjectionPoints = new Dictionary <Type, CustomPostProcessInjectionPoint>();

            var ppVolumeTypes = TypeCache.GetTypesDerivedFrom <CustomPostProcessVolumeComponent>();

            foreach (var ppVolumeType in ppVolumeTypes.Where(t => !t.IsAbstract))
            {
                var comp = ScriptableObject.CreateInstance(ppVolumeType) as CustomPostProcessVolumeComponent;
                ppVolumeTypeInjectionPoints[ppVolumeType] = comp.injectionPoint;
                CoreUtils.Destroy(comp);
            }

            var globalSettings = serializedObject.targetObject as HDRenderPipelineGlobalSettings;

            InitList(ref uiBeforeTransparentCustomPostProcesses, globalSettings.beforeTransparentCustomPostProcesses, "After Opaque And Sky", CustomPostProcessInjectionPoint.AfterOpaqueAndSky);
            InitList(ref uiBeforePostProcessCustomPostProcesses, globalSettings.beforePostProcessCustomPostProcesses, "Before Post Process", CustomPostProcessInjectionPoint.BeforePostProcess);
            InitList(ref uiAfterPostProcessCustomPostProcesses, globalSettings.afterPostProcessCustomPostProcesses, "After Post Process", CustomPostProcessInjectionPoint.AfterPostProcess);
            InitList(ref uiBeforeTAACustomPostProcesses, globalSettings.beforeTAACustomPostProcesses, "Before TAA", CustomPostProcessInjectionPoint.BeforeTAA);

            void InitList(ref ReorderableList reorderableList, List <string> customPostProcessTypes, string headerName, CustomPostProcessInjectionPoint injectionPoint)
            {
                // Sanitize the list
                customPostProcessTypes.RemoveAll(s => Type.GetType(s) == null);

                reorderableList = new ReorderableList(customPostProcessTypes, typeof(string));
                reorderableList.drawHeaderCallback = (rect) =>
                                                     EditorGUI.LabelField(rect, headerName, EditorStyles.label);
                reorderableList.drawElementCallback = (rect, index, isActive, isFocused) =>
                {
                    rect.height = EditorGUIUtility.singleLineHeight;
                    var elemType = Type.GetType(customPostProcessTypes[index]);
                    EditorGUI.LabelField(rect, elemType.ToString(), EditorStyles.boldLabel);
                };
                reorderableList.onAddCallback = (list) =>
                {
                    var menu = new GenericMenu();

                    foreach (var kp in ppVolumeTypeInjectionPoints)
                    {
                        if (kp.Value == injectionPoint && !customPostProcessTypes.Contains(kp.Key.AssemblyQualifiedName))
                        {
                            menu.AddItem(new GUIContent(kp.Key.ToString()), false, () =>
                            {
                                Undo.RegisterCompleteObjectUndo(serializedObject.targetObject, $"Added {kp.Key.ToString()} Custom Post Process");
                                customPostProcessTypes.Add(kp.Key.AssemblyQualifiedName);
                            });
                        }
                    }

                    if (menu.GetItemCount() == 0)
                    {
                        menu.AddDisabledItem(new GUIContent("No Custom Post Process Available"));
                    }

                    menu.ShowAsContext();
                    EditorUtility.SetDirty(serializedObject.targetObject);
                };
                reorderableList.onRemoveCallback = (list) =>
                {
                    Undo.RegisterCompleteObjectUndo(serializedObject.targetObject, $"Removed {list.list[list.index].ToString()} Custom Post Process");
                    customPostProcessTypes.RemoveAt(list.index);
                    EditorUtility.SetDirty(serializedObject.targetObject);
                };
                reorderableList.elementHeightCallback = _ => EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                reorderableList.onReorderCallback     = (list) =>
                {
                    EditorUtility.SetDirty(serializedObject.targetObject);
                };
            }
        }
예제 #36
0
    /// <summary>
    /// Clear the context menu list.
    /// </summary>

    static public void Clear()
    {
        mEntries.Clear();
        mMenu = null;
    }
예제 #37
0
    private void updateToolbar()
    {
        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);

        // If there are no cutscenes, then only give option to create a new cutscene.
        if (GUILayout.Button(CREATE, EditorStyles.toolbarDropDown, GUILayout.Width(60)))
        {
            GenericMenu createMenu = new GenericMenu();
            createMenu.AddItem(new_cutscene, false, openCutsceneCreatorWindow);

            if (cutscene != null)
            {
                createMenu.AddSeparator(string.Empty);

                foreach (Type type in DirectorHelper.GetAllSubTypes(typeof(TrackGroup)))
                {
                    TrackGroupContextData userData = getContextDataFromType(type);
                    string text = string.Format(userData.Label);
                    createMenu.AddItem(new GUIContent(text), false, AddTrackGroup, userData);
                }
            }

            createMenu.DropDown(new Rect(5, TOOLBAR_HEIGHT, 0, 0));
        }

        // Cutscene selector
        cachedCutscenes = FindObjectsOfType <Cutscene>();
        if (cachedCutscenes != null && cachedCutscenes.Length > 0)
        {
            // Get cutscene names
            GUIContent[] cutsceneNames = new GUIContent[cachedCutscenes.Length];
            for (int i = 0; i < cachedCutscenes.Length; i++)
            {
                cutsceneNames[i] = new GUIContent(cachedCutscenes[i].name);
            }

            // Sort alphabetically
            Array.Sort(cutsceneNames, delegate(GUIContent content1, GUIContent content2)
            {
                return(string.Compare(content1.text, content2.text));
            });

            int count = 1;
            // Resolve duplicate names
            for (int i = 0; i < cutsceneNames.Length - 1; i++)
            {
                int next = i + 1;
                while (next < cutsceneNames.Length && string.Compare(cutsceneNames[i].text, cutsceneNames[next].text) == 0)
                {
                    cutsceneNames[next].text = string.Format("{0} (duplicate {1})", cutsceneNames[next].text, count++);
                    next++;
                }
                count = 1;
            }

            Array.Sort(cachedCutscenes, delegate(Cutscene c1, Cutscene c2)
            {
                return(string.Compare(c1.name, c2.name));
            });

            // Find the currently selected cutscene.
            for (int i = 0; i < cachedCutscenes.Length; i++)
            {
                if (cutscene != null && cutscene.GetInstanceID() == cachedCutscenes[i].GetInstanceID())
                {
                    popupSelection = i;
                }
            }

            // Show the popup
            int tempPopup = EditorGUILayout.Popup(popupSelection, cutsceneNames, EditorStyles.toolbarPopup);
            if (cutscene == null || tempPopup != popupSelection || cutsceneInstanceID != cachedCutscenes[Math.Min(tempPopup, cachedCutscenes.Length - 1)].GetInstanceID())
            {
                popupSelection = tempPopup;
                popupSelection = Math.Min(popupSelection, cachedCutscenes.Length - 1);
                FocusCutscene(cachedCutscenes[popupSelection]);
            }
        }
        if (cutscene != null)
        {
            if (GUILayout.Button(pickerImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
            {
                Selection.activeObject = cutscene;
            }
            if (GUILayout.Button(refreshImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
            {
                cutscene.Refresh();
            }

            if (Event.current.control && Event.current.keyCode == KeyCode.Space)
            {
                cutscene.Refresh();
                Event.current.Use();
            }
        }
        GUILayout.FlexibleSpace();
        GUILayout.Label(Cutscene.frame.ToString());
        if (betaFeaturesEnabled)
        {
            Texture resizeTexture = cropImage;
            if (directorControl.ResizeOption == DirectorEditor.ResizeOption.Scale)
            {
                resizeTexture = scaleImage;
            }
            Rect resizeRect = GUILayoutUtility.GetRect(new GUIContent(resizeTexture), EditorStyles.toolbarDropDown, GUILayout.Width(32));
            if (GUI.Button(resizeRect, new GUIContent(resizeTexture, "Resize Option"), EditorStyles.toolbarDropDown))
            {
                GenericMenu resizeMenu = new GenericMenu();

                string[] names = Enum.GetNames(typeof(DirectorEditor.ResizeOption));

                for (int i = 0; i < names.Length; i++)
                {
                    resizeMenu.AddItem(new GUIContent(names[i]), directorControl.ResizeOption == (DirectorEditor.ResizeOption)i, chooseResizeOption, i);
                }

                resizeMenu.DropDown(new Rect(resizeRect.x, TOOLBAR_HEIGHT, 0, 0));
            }
        }

        bool tempSnapping = GUILayout.Toggle(isSnappingEnabled, snapImage, EditorStyles.toolbarButton, GUILayout.Width(24));

        if (tempSnapping != isSnappingEnabled)
        {
            isSnappingEnabled = tempSnapping;
            directorControl.IsSnappingEnabled = isSnappingEnabled;
        }

        GUILayout.Space(10f);

        if (GUILayout.Button(rescaleImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.Rescale();
        }
        if (GUILayout.Button(new GUIContent(zoomInImage, "Zoom In"), EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.ZoomIn();
        }
        if (GUILayout.Button(zoomOutImage, EditorStyles.toolbarButton, GUILayout.Width(24)))
        {
            directorControl.ZoomOut();
        }
        GUILayout.Space(10f);

        Color temp = GUI.color;

        GUI.color = directorControl.InPreviewMode ? Color.red : temp;

        directorControl.InPreviewMode = GUILayout.Toggle(directorControl.InPreviewMode, string.Format("{0} {1}", PREVIEW_MODE, Cutscene.frameRate), EditorStyles.toolbarButton, GUILayout.Width(150));
        GUI.color = temp;
        GUILayout.Space(10);

        if (GUILayout.Button(settingsImage, EditorStyles.toolbarButton, GUILayout.Width(30)))
        {
            GetWindow <DirectorSettingsWindow>();
        }
        var helpWindowType = Type.GetType("CinemaSuite.CinemaSuiteWelcome");

        if (helpWindowType != null)
        {
            if (GUILayout.Button(new GUIContent("?", "Help"), EditorStyles.toolbarButton))
            {
                GetWindow(helpWindowType);
            }
        }
        EditorGUILayout.EndHorizontal();
    }
예제 #38
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                if (e.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    graphEditor.OnDropObjects(DragAndDrop.objectReferences);
                }
                break;

            case EventType.MouseMove:
                //Keyboard commands will not get correct mouse position from Event
                lastMousePosition = e.mousePosition;
                break;

            case EventType.ScrollWheel:
                float oldZoom = zoom;
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                if (NodeEditorPreferences.GetSettings().zoomToMouse)
                {
                    panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput && draggedOutput.CanConnectTo(hoveredPort))
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node    = Selection.objects[i] as XNode.Node;
                                Vector2    initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round(pos.x / 16) * 16);
                                pos.y = (Mathf.Round(pos.y / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    panOffset += e.delta * zoom;
                    isPanning  = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }

                        // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
                        isDoubleClick = (e.clickCount == 2);

                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                            EditorGUIUtility.editingTextField = false;
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);

                        // Double click to center node
                        if (isDoubleClick)
                        {
                            Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
                            panOffset = -hoveredNode.position - nodeDimension;
                        }
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            e.Use();     // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
                        }
                        else if (!IsHoveringNode)
                        {
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (NodeEditorUtilities.IsMac())
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Copy")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        CopySelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Paste")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        PasteNodes(WindowToGridPosition(lastMousePosition));
                    }
                    e.Use();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
예제 #39
0
        protected virtual void SceneViewGUICallback(UnityObject target, SceneView sceneView)
        {
            VisualEffect effect = ((VisualEffect)targets[0]);

            var buttonWidth = GUILayout.Width(50);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button(Contents.GetIcon(Contents.Icon.Stop), buttonWidth))
            {
                effect.ControlStop();
            }
            if (effect.pause)
            {
                if (GUILayout.Button(Contents.GetIcon(Contents.Icon.Play), buttonWidth))
                {
                    effect.ControlPlayPause();
                }
            }
            else
            {
                if (GUILayout.Button(Contents.GetIcon(Contents.Icon.Pause), buttonWidth))
                {
                    effect.ControlPlayPause();
                }
            }


            if (GUILayout.Button(Contents.GetIcon(Contents.Icon.Step), buttonWidth))
            {
                effect.ControlStep();
            }
            if (GUILayout.Button(Contents.GetIcon(Contents.Icon.Restart), buttonWidth))
            {
                effect.ControlRestart();
            }
            GUILayout.EndHorizontal();

            float playRate = effect.playRate * VisualEffectControl.playRateToValue;

            GUILayout.BeginHorizontal();
            GUILayout.Label(Contents.playRate, GUILayout.Width(44));
            playRate        = EditorGUILayout.PowerSlider("", playRate, VisualEffectControl.minSlider, VisualEffectControl.maxSlider, VisualEffectControl.sliderPower, GUILayout.Width(124));
            effect.playRate = playRate * VisualEffectControl.valueToPlayRate;

            var eventType = Event.current.type;

            if (EditorGUILayout.DropdownButton(Contents.setPlayRate, FocusType.Passive, GUILayout.Width(36)))
            {
                GenericMenu menu = new GenericMenu();
                foreach (var value in VisualEffectControl.setPlaybackValues)
                {
                    menu.AddItem(EditorGUIUtility.TextContent(string.Format("{0}%", value)), false, SetPlayRate, value);
                }
                var savedEventType = Event.current.type;
                Event.current.type = eventType;
                Rect buttonRect = GUILayoutUtility.GetLastRect();
                Event.current.type = savedEventType;
                menu.DropDown(buttonRect);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            GUILayout.Label("Show Bounds", GUILayout.Width(192));

            VisualEffectUtility.renderBounds = EditorGUILayout.Toggle(VisualEffectUtility.renderBounds, GUILayout.Width(18));

            GUILayout.EndHorizontal();
        }
예제 #40
0
    public void OnGUI()
    {
        var valid = true;

        EditorSteamManager.EnforceInstance();
        EditorSteamManager.PrepareSteamworks();

        if (SteamUnity.Instance == null)
        {
            SteamUnity.Instance = GameObject.FindObjectOfType <SteamUnity>();
        }
        if (SteamUnity.Instance == null)
        {
            SteamUnity.Instance = (new GameObject("SteamUnity")).AddComponent <SteamUnity>();
        }
        if (SteamUnity.Instance == null)
        {
            return;
        }

        EditorGUILayout.HelpBox("Steam", MessageType.None);

        var steamid   = (int)((ulong)SteamUser.GetSteamID().m_SteamID);
        var steamname = SteamFriends.GetPersonaName();

        GUILayout.Label(string.Format("Initialized: {0}", EditorSteamManager.Instance.Initialized.ToString()));
        GUILayout.Label(string.Format("Steam Running: {0}", SteamAPI.IsSteamRunning()));
        GUILayout.Label(string.Format("Steam ID: {0}", steamid));
        GUILayout.Label(string.Format("Steam User: {0}", steamname));

        if (GUILayout.Button("Break Busy"))
        {
            SteamUnity.Instance.busy = false;
        }

        EditorGUILayout.HelpBox("Steam Published Files", MessageType.None);

        if (GUILayout.Button("Scan Published Items"))
        {
            SteamUnity.Instance.QueryPublishedItems();
        }

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Create Workshop Item"))
        {
            SteamUnity.Instance.CreateItem();
        }

        if (GUILayout.Button("Submit Item"))
        {
            SteamUnity.Instance.SubmitItem(textTitle, textDescription, textTag, textManifest, texturePreview);
        }

        GUILayout.EndHorizontal();

        EditorGUILayout.HelpBox("Steam Published Items", MessageType.None);

        var published = SteamUnity.Instance.GetPublishedItems();
        var working   = SteamUnity.Instance.GetWorking();

        for (int i = 0; i < published.Count; ++i)
        {
            var item = published[i];

            GUILayout.BeginHorizontal();
            GUILayout.Label(string.Format("{0} ({1})", item.m_rgchTitle, item.m_nPublishedFileId.m_PublishedFileId.ToString()), GUILayout.Width(200));

            if (GUILayout.Button("Select"))
            {
                SteamUnity.Instance.SelectWorking(item.m_nPublishedFileId);

                var details = SteamUnity.Instance.GetWorkingDetails();

                textTitle       = details.m_rgchTitle;
                textDescription = details.m_rgchDescription;
                textTag         = details.m_rgchTags;
                textManifest    = details.m_pchFileName;
            }

            GUILayout.EndHorizontal();
        }

        EditorGUILayout.HelpBox("Steam Submission", MessageType.None);

        if (working != PublishedFileId_t.Invalid)
        {
            var workingDetails = SteamUnity.Instance.GetWorkingDetails();

            if (workingDetails.m_nPublishedFileId != PublishedFileId_t.Invalid)
            {
                GUILayout.Label(string.Format("{0} ({1})", workingDetails.m_rgchTitle, workingDetails.m_nPublishedFileId), GUILayout.Width(200));

                GUILayout.BeginHorizontal();
                GUILayout.Label("Title", GUILayout.Width(200));
                textTitle = GUILayout.TextField(textTitle);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Description", GUILayout.Width(200));
                textDescription = GUILayout.TextField(textDescription);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Tag", GUILayout.Width(200));
                textTag = GUILayout.TextField(textTag);
                if (textTag != "character" && textTag != "world")
                {
                    textTag = "world";
                }
                GUILayout.EndHorizontal();

                EditorGUILayout.Separator();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Folder", GUILayout.Width(200));
                textManifest = GUILayout.TextField(textManifest);
                var menu = new GenericMenu();
                if (GUILayout.Button("Select Bundle"))
                {
                    var exportsFolder = Path.GetFullPath(Path.Combine(Application.dataPath, "../Exports"));
                    var subFolder     = textTag == "world" ? "Worlds" : "Characters";
                    var contentFolder = Path.Combine(exportsFolder, subFolder);

                    if (Directory.Exists(contentFolder))
                    {
                        var contentFiles = new List <string>(Directory.GetFiles(contentFolder, "*.manifest"));

                        foreach (var content in contentFiles)
                        {
                            if (content == "Characters.manifest" || content == "Worlds.manifest")
                            {
                                continue;
                            }

                            var contentName = Path.GetFileNameWithoutExtension(content);

                            menu.AddItem(new GUIContent(contentName), textManifest == content, o => { textManifest = content; }, null);
                        }

                        menu.ShowAsContext();
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Preview Texture", GUILayout.Width(200));
                texturePreview = EditorGUILayout.ObjectField(texturePreview, typeof(Texture2D), true) as Texture2D;
                GUILayout.EndHorizontal();
            }
        }
    }
예제 #41
0
            private void VariableField <T>(Action <T> converter, Action field) where T : Value
            {
                useVariable = EditorGUILayout.Toggle("Use Variable", useVariable);
                if (useVariable)
                {
                    useLocal = EditorGUILayout.Toggle("Use Local", useLocal);
                    if (useLocal)
                    {
                        variableObject = _content.transform.Find("LocalVariable")?.gameObject;
                    }
                    else
                    {
                        variableObject = (GameObject)EditorGUILayout.ObjectField(parameterName, variableObject,
                                                                                 typeof(GameObject),
                                                                                 true);
                    }

                    if (variableObject != null && GUILayout.Button("変数を選択"))
                    {
                        Value[]     values = GetValueComponents(variableObject);
                        GenericMenu menu   = new GenericMenu();
                        foreach (Value value in values)
                        {
                            if (value is T)
                            {
                                menu.AddItem(
                                    new GUIContent(value.valueName + " " + (value.constValue ? "(const)" : "")),
                                    false,
                                    data =>
                                {
                                    Value select = (Value)data;
                                    variable     = select;
                                }, value);
                            }
                        }

                        menu.ShowAsContext();
                    }
                    else if (variableObject == null)
                    {
                        EditorGUILayout.HelpBox("オブジェクトが見つかりません。", MessageType.Error);
                    }

                    if (variable is T conv)
                    {
                        converter.Invoke(conv);
                    }
                    else if (variable == null)
                    {
                        EditorGUILayout.HelpBox("変数が設定されていません。", MessageType.Error);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox("サポート外の変数です。<" + variable.valueName + ">", MessageType.Error);
                    }
                }
                else
                {
                    field.Invoke();
                }
            }
예제 #42
0
 public override void Init(IControl parent)
 {
     parent.ContextClick += delegate(object target, Event evt, TimelineWindow.TimelineState state)
     {
         float       tolerance   = 0.25f / state.frameRate;
         GenericMenu genericMenu = new GenericMenu();
         genericMenu.AddItem(EditorGUIUtility.TextContent("Insert/Frame/Single"), false, delegate
         {
             Gaps.Insert(state.timeline, state.time, (double)(1f / state.frameRate), tolerance);
             state.Refresh(true);
         });
         int[] array = new int[]
         {
             5,
             10,
             25,
             100
         };
         for (int num = 0; num != array.Length; num++)
         {
             float f = (float)array[num];
             genericMenu.AddItem(EditorGUIUtility.TextContent("Insert/Frame/" + array[num] + " Frames"), false, delegate
             {
                 Gaps.Insert(state.timeline, state.time, (double)(f / state.frameRate), tolerance);
                 state.Refresh(true);
             });
         }
         Vector2 playRangeTime = state.playRangeTime;
         if (playRangeTime.y > playRangeTime.x)
         {
             genericMenu.AddItem(EditorGUIUtility.TextContent("Insert/Selected Time"), false, delegate
             {
                 Gaps.Insert(state.timeline, (double)playRangeTime.x, (double)(playRangeTime.y - playRangeTime.x), tolerance);
                 state.Refresh(true);
             });
         }
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Clips Ending Before"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => x.end < state.time + (double)tolerance, state);
         });
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Clips Starting Before"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => x.start < state.time + (double)tolerance, state);
         });
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Clips Ending After"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => x.end - state.time >= (double)(-(double)tolerance), state);
         });
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Clips Starting After"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => x.start - state.time >= (double)(-(double)tolerance), state);
         });
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Clips Intersecting"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => x.start <= state.time && state.time <= x.end, state);
         });
         genericMenu.AddItem(EditorGUIUtility.TextContent("Select/Blends Intersecting"), false, delegate
         {
             TrackheadContextMenu.SelectMenuCallback((TimelineClip x) => TrackheadContextMenu.SelectBlendingIntersecting(x, state.time), state);
         });
         genericMenu.ShowAsContext();
         return(base.ConsumeEvent());
     };
 }
        private Rect DrawStack(Rect rect, KeyValuePair <Texture, List <KeyValuePair <Component, Behaviour> > > stack)
        {
            Texture icon          = stack.Key;
            int     stackCount    = stack.Value.Count;
            bool    stackMultiple = stackCount > 1;

            Component[] components = stack.Value.Select(x => x.Key).ToArray();
            Behaviour[] behaviours = stack.Value.Select(x => x.Value).ToArray();
            bool        disabled   = behaviours.Any(x => (x != null) && !x.enabled);

            Rect right = new Rect(rect)
            {
                xMin = rect.xMax - 16, width = 16
            };

            GUI.color = disabled ? new Color(1, 1, 1, 0.2f) : Color.white;
            GUI.DrawTexture(right, icon);
            GUI.color = Color.white;

            if (stackMultiple)
            {
                Rect rectNumber = new Rect(right);
                rectNumber.x -= 1;
                GUIContent content = new GUIContent(stackCount.ToString());
                GUI.color = new Color(0, 0, 0, 0.5f);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x - 2
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x + 2
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x - 1, y = rectNumber.y - 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x + 1, y = rectNumber.y - 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x - 1, y = rectNumber.y + 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x + 1, y = rectNumber.y + 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x - 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    x = rectNumber.x + 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    y = rectNumber.y - 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.Label(new Rect(rectNumber)
                {
                    y = rectNumber.y + 1
                }, content, HierarchyProEditorStyles.LabelNumber);
                GUI.color = Color.white;
                GUI.Label(rectNumber, content, HierarchyProEditorStyles.LabelNumber);
            }

            if (GUI.Button(right, GUIContent.none, GUIStyle.none))
            {
                if (Event.current.button == 0)
                {
                    if (stackMultiple)
                    {
                        if (Event.current.shift)
                        {
                            if (icon == HierarchyProEditorIcons.ScriptCS)
                            {
                                MonoScript[] scripts = behaviours.Select(x => MonoScript.FromMonoBehaviour(x as MonoBehaviour)).Where(x => x != null).ToArray();
                                if (!scripts.Any())
                                {
                                    HierarchyProEditorWindow.EditorWindow.ShowNotification(new GUIContent("No MonoScripts"));
                                }
                                else
                                {
                                    GenericMenu menu = new GenericMenu();
                                    menu.AddDisabledItem(new GUIContent("Open Script"));
                                    menu.AddSeparator("");
                                    foreach (MonoScript script in scripts)
                                    {
                                        menu.AddItem(new GUIContent(string.Format("{0}.cs", script.GetClass().Name)), false, this.OpenScript, script);
                                    }
                                    menu.ShowAsContext();
                                    Event.current.Use();
                                }
                            }
                        }
                        else
                        {
                            MonoBehaviour[] monoBehaviours = behaviours.OfType <MonoBehaviour>().ToArray();
                            if (!monoBehaviours.Any())
                            {
                                HierarchyProEditorWindow.EditorWindow.ShowNotification(new GUIContent("No Behaviours"));
                            }
                            else
                            {
                                GenericMenu menu = new GenericMenu();
                                menu.AddDisabledItem(new GUIContent("Enable \u2215 Disable"));
                                menu.AddSeparator("");
                                foreach (Behaviour behaviour in behaviours)
                                {
                                    MonoBehaviour monoBehvaiour = behaviour as MonoBehaviour;
                                    if (monoBehvaiour == null)
                                    {
                                        continue;
                                    }
                                    MonoScript script = MonoScript.FromMonoBehaviour(monoBehvaiour);
                                    menu.AddItem(new GUIContent(script.GetClass().Name), behaviour.enabled, this.ToggleScript, behaviour);
                                }
                                menu.AddSeparator("");
                                menu.AddItem(new GUIContent("Enable All"), false, this.EnableAllScripts, behaviours);
                                menu.AddItem(new GUIContent("Disable All"), false, this.DisableAllScripts, behaviours);
                                menu.ShowAsContext();
                                Event.current.Use();
                            }
                        }
                    }
                    else
                    {
                        Component singleComponent = components.First();
                        Behaviour singleBehaviour = behaviours.First();
                        if (Event.current.shift)
                        {
                            if (icon == HierarchyProEditorIcons.ScriptCS)
                            {
                                MonoScript script = MonoScript.FromMonoBehaviour(singleComponent as MonoBehaviour);
                                AssetDatabase.OpenAsset(script, 1);
                            }
                            else if (singleComponent is Light)
                            {
                                EditorWindow lightingWindow = HierarchyProEditorComponents.GetLightingWindow();
                                lightingWindow.Show();
                            }
                        }
                        else
                        {
                            if (singleBehaviour != null)
                            {
                                singleBehaviour.enabled = !singleBehaviour.enabled;
                            }
                        }
                    }
                }
            }

            right.x -= 16;
            return(right);
        }
예제 #44
0
        /// <summary>
        /// Draws the style asset field.
        /// </summary>
        /// <param name="property">Property.</param>
        /// <param name="onSelect">On select.</param>
        public static void DrawAssetField <T>(Rect position, GUIContent label, SerializedProperty property, Action <T, bool> onSelect) where T : UnityEngine.Object
        {
            // Object field.
            Rect rField = new Rect(position.x, position.y, position.width - 16, position.height);

            EditorGUI.BeginChangeCheck();
            EditorGUI.PropertyField(rField, property, label);
            if (EditorGUI.EndChangeCheck())
            {
                property.serializedObject.ApplyModifiedProperties();
                onSelect(property.objectReferenceValue as T, false);
            }

            // Popup to select style asset in project.
            Rect rPopup = new Rect(position.x + rField.width, position.y + 4, 16, position.height - 4);

            if (GUI.Button(rPopup, EditorGUIUtility.FindTexture("icon dropdown"), EditorStyles.label))
            {
                // Create style asset.
                GenericMenu menu = new GenericMenu();

                // If asset is ScriptableObject, add item to create new one.
                if (typeof(ScriptableObject).IsAssignableFrom(typeof(T)))
                {
                    menu.AddItem(new GUIContent(string.Format("Create New {0}", typeof(T).Name)), false, () =>
                    {
                        // Open save file dialog.
                        string filename = AssetDatabase.GenerateUniqueAssetPath(string.Format("Assets/New {0}.asset", typeof(T).Name));
                        string path     = EditorUtility.SaveFilePanelInProject(string.Format("Create New {0}", typeof(T).Name), Path.GetFileName(filename), "asset", "");
                        if (path.Length == 0)
                        {
                            return;
                        }

                        // Create and save a new builder asset.
                        T asset = ScriptableObject.CreateInstance(typeof(T)) as T;
                        AssetDatabase.CreateAsset(asset, path);
                        AssetDatabase.SaveAssets();
                        EditorGUIUtility.PingObject(asset);

                        property.objectReferenceValue = asset;
                        property.serializedObject.ApplyModifiedProperties();
                        property.serializedObject.Update();
                        onSelect(asset, true);
                    });
                    menu.AddSeparator("");
                }

                // Unselect style asset.
                menu.AddItem(
                    new GUIContent("-"),
                    !property.hasMultipleDifferentValues && !property.objectReferenceValue,
                    () =>
                {
                    property.objectReferenceValue = null;
                    property.serializedObject.ApplyModifiedProperties();
                    property.serializedObject.Update();
                    onSelect(null, false);
                }
                    );

                // Select style asset.
                foreach (string path in AssetDatabase.FindAssets("t:" + typeof(T).Name).Select(x => AssetDatabase.GUIDToAssetPath(x)))
                {
                    string assetName     = Path.GetFileNameWithoutExtension(path);
                    string displayedName = assetName.Replace(" - ", "/");
                    bool   active        = !property.hasMultipleDifferentValues && property.objectReferenceValue && (property.objectReferenceValue.name == assetName);
                    menu.AddItem(
                        new GUIContent(displayedName),
                        active,
                        x =>
                    {
                        T asset = AssetDatabase.LoadAssetAtPath((string)x, typeof(T)) as T;
                        property.objectReferenceValue = asset;
                        property.serializedObject.ApplyModifiedProperties();
                        property.serializedObject.Update();
                        onSelect(asset, false);
                    },
                        path
                        );
                }

                menu.ShowAsContext();
            }
        }
        /**
         *      retrieve mouse events for this node in this AssetGraoh window.
         */
        private void HandleNodeEvent()
        {
            switch (Event.current.type)
            {
            /*
             *              handling release of mouse drag from this node to another node.
             *              this node doesn't know about where the other node is. the master only knows.
             *              only emit event.
             */
            case EventType.Ignore: {
                NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECTION_OVERED, this, Event.current.mousePosition, null));
                break;
            }

            /*
             *      handling drag.
             */
            case EventType.MouseDrag: {
                NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_MOVING, this, Event.current.mousePosition, null));
                break;
            }

            /*
             *      check if the mouse-down point is over one of the connectionPoint in this node.
             *      then emit event.
             */
            case EventType.MouseDown: {
                ConnectionPointData result = IsOverConnectionPoint(Event.current.mousePosition);

                if (result != null)
                {
                    if (scaleFactor == SCALE_MAX)
                    {
                        NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECT_STARTED, this, Event.current.mousePosition, result));
                    }
                    break;
                }
                break;
            }
            }

            /*
             *      retrieve mouse events for this node in|out of this AssetGraoh window.
             */
            switch (Event.current.rawType)
            {
            case EventType.MouseUp: {
                bool eventRaised = false;
                // if mouse position is on the connection point, emit mouse raised event.
                Action <ConnectionPointData> raiseEventIfHit = (ConnectionPointData point) => {
                    // Only one connectionPoint raise event at one mouseup event
                    if (eventRaised)
                    {
                        return;
                    }
//						var region = point.Region;
//						var globalConnectonPointRect = new Rect(region.x, region.y, region.width, region.height);
                    if (point.Region.Contains(Event.current.mousePosition))
                    {
                        NodeGUIUtility.NodeEventHandler(
                            new NodeEvent(NodeEvent.EventType.EVENT_NODE_CONNECTION_RAISED,
                                          this, Event.current.mousePosition, point));
                        eventRaised = true;
                        return;
                    }
                };
                m_data.InputPoints.ForEach(raiseEventIfHit);
                m_data.OutputPoints.ForEach(raiseEventIfHit);
                if (!eventRaised)
                {
                    NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_TOUCHED,
                                                                  this, Event.current.mousePosition, null));
                }
                break;
            }
            }

            /*
             *      right click to open Context menu
             */
            if (scaleFactor == SCALE_MAX)
            {
                if (Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseUp && Event.current.button == 1))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(
                        new GUIContent("Delete"),
                        false,
                        () => {
                        NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CLOSE_TAPPED, this, Vector2.zero, null));
                    }
                        );
                    menu.ShowAsContext();
                    Event.current.Use();
                }
            }
        }
 public void AddItemsToMenu(GenericMenu menu)
 {
     menu.AddItem(EditorGUIUtility.TrTextContent("Internal Log"), false, ShowInternalLog);
 }
예제 #47
0
    static void OpenContextMenu(Vector2 pos, SceneView sceneView)
    {
        var invertedPos = new Vector2(pos.x, sceneView.position.height - 16 - pos.y);

        GenericMenu contextMenu = new GenericMenu();
        GameObject  obj         = null;
        int         matIndex;

        Dictionary <Transform, List <Transform> > parentChildsDict = new Dictionary <Transform, List <Transform> >();

        GameObject[] currArray = null;

        for (int i = 0; i <= MAX_OBJ_FOUND; i++)
        {
            if (parentChildsDict.Count > 0)
            {
                currArray = new GameObject[parentChildsDict.Count];
                int arrayIndex = 0;
                foreach (var parent in parentChildsDict)
                {
                    currArray[arrayIndex] = parent.Key.gameObject;
                    arrayIndex++;
                }
            }

            obj = PickObjectOnPos(sceneView.camera, ~0, invertedPos, currArray, null, out matIndex);
            if (obj != null)
            {
                parentChildsDict[obj.transform] = new List <Transform>();

                var currentParent = obj.transform.parent;
                var lastParent    = obj.transform;
                List <Transform> currentChilds;
                while (currentParent != null)
                {
                    if (parentChildsDict.TryGetValue(currentParent, out currentChilds))
                    {
                        currentChilds.Add(lastParent);
                    }
                    else
                    {
                        parentChildsDict.Add(currentParent, new List <Transform>()
                        {
                            lastParent
                        });
                    }

                    lastParent    = currentParent;
                    currentParent = currentParent.parent;
                }
            }
            else
            {
                break;
            }
        }

        foreach (var parentChild in parentChildsDict.Where(keyValue => keyValue.Key.parent == null))
        {
            CreateMenuRecu(contextMenu, parentChild.Key, "", parentChildsDict);
        }

        if (parentChildsDict.Count == 0)
        {
            AddMenuItem(contextMenu, "None", null);
        }

        contextMenu.DropDown(new Rect(pos, Vector2.zero));
    }
예제 #48
0
            protected override void ContextClickedItem(int id)
            {
                var item = FindItem(id, rootItem);

                if (item == null)
                {
                    return;
                }

                if (item is DeviceItem deviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.openDebugView, false, () => InputDeviceDebuggerWindow.CreateOrShowExisting(deviceItem.device));
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = deviceItem.device.description.ToJson());
                    menu.AddItem(Contents.removeDevice, false, () => InputSystem.RemoveDevice(deviceItem.device));
                    if (deviceItem.device.enabled)
                    {
                        menu.AddItem(Contents.disableDevice, false, () => InputSystem.DisableDevice(deviceItem.device));
                    }
                    else
                    {
                        menu.AddItem(Contents.enableDevice, false, () => InputSystem.EnableDevice(deviceItem.device));
                    }
                    menu.AddItem(Contents.syncDevice, false, () => InputSystem.TrySyncDevice(deviceItem.device));
                    menu.AddItem(Contents.softResetDevice, false, () => ResetDevice(deviceItem.device, false));
                    menu.AddItem(Contents.hardResetDevice, false, () => ResetDevice(deviceItem.device, true));
                    menu.ShowAsContext();
                }

                if (item is UnsupportedDeviceItem unsupportedDeviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = unsupportedDeviceItem.description.ToJson());
                    menu.ShowAsContext();
                }

                if (item is LayoutItem layoutItem)
                {
                    var layout = EditorInputControlLayoutCache.TryGetLayout(layoutItem.layoutName);
                    if (layout != null)
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(Contents.copyLayoutAsJSON, false,
                                     () => EditorGUIUtility.systemCopyBuffer = layout.ToJson());
                        if (layout.isDeviceLayout)
                        {
                            menu.AddItem(Contents.createDeviceFromLayout, false,
                                         () => InputSystem.AddDevice(layout.name));
                            menu.AddItem(Contents.generateCodeFromLayout, false, () =>
                            {
                                var fileName   = EditorUtility.SaveFilePanel("Generate InputDevice Code", "", "Fast" + layoutItem.layoutName, "cs");
                                var isInAssets = fileName.StartsWith(Application.dataPath, StringComparison.OrdinalIgnoreCase);
                                if (isInAssets)
                                {
                                    fileName = "Assets/" + fileName.Substring(Application.dataPath.Length + 1);
                                }
                                if (!string.IsNullOrEmpty(fileName))
                                {
                                    var code = InputLayoutCodeGenerator.GenerateCodeFileForDeviceLayout(layoutItem.layoutName, fileName, prefix: "Fast");
                                    File.WriteAllText(fileName, code);
                                    if (isInAssets)
                                    {
                                        AssetDatabase.Refresh();
                                    }
                                }
                            });
                        }
                        menu.ShowAsContext();
                    }
                }
            }
예제 #49
0
        ///----------------------------------------------------------------------------------------------

        //EDIT MENU
        static GenericMenu GetToolbarMenu_Edit(Graph graph, GraphOwner owner)
        {
            var menu = new GenericMenu();

            //Bind
            if (!Application.isPlaying && owner != null && !owner.graphIsBound)
            {
                menu.AddItem(new GUIContent("Bind To Owner"), false, () =>
                {
                    if (EditorUtility.DisplayDialog("Bind Graph", "This will make a local copy of the graph, bound to the owner.\n\nThis allows you to make local changes and assign scene object references directly.\n\nNote that you can also use scene object references through the use of Blackboard Variables.\n\nBind Graph?", "YES", "NO"))
                    {
                        Undo.RecordObject(owner, "New Local Graph");
                        owner.SetBoundGraphReference(owner.graph);
                        EditorUtility.SetDirty(owner);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Bind To Owner"));
            }

            //Save to asset
            if (owner != null && owner.graphIsBound)
            {
                menu.AddItem(new GUIContent("Save To Asset"), false, () =>
                {
                    var newGraph = (Graph)EditorUtils.CreateAsset(graph.GetType(), true);
                    if (newGraph != null)
                    {
                        EditorUtility.CopySerialized(graph, newGraph);
                        newGraph.Validate();
                        AssetDatabase.SaveAssets();

                        //SL--------------
                        NestedUtility.SaveToAsset(graph, newGraph);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Save To Asset"));
            }

            //Create defined vars
            if (graph.blackboard != null)
            {
                menu.AddItem(new GUIContent("Promote Defined Parameters To Variables"), false, () =>
                {
                    if (EditorUtility.DisplayDialog("Promote Defined Parameters", "This will fill the current Blackboard with a Variable for each defined Parameter in the graph.\nContinue?", "YES", "NO"))
                    {
                        graph.PromoteDefinedParametersToVariables(graph.blackboard);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Promote Defined Parameters To Variables"));
            }

            return(menu);
        }
예제 #50
0
        void DrawScriptView(FungusScript fungusScript)
        {
            EditorUtility.SetDirty(fungusScript);

            Sequence[] sequences = fungusScript.GetComponentsInChildren <Sequence>();

            Rect scrollViewRect = new Rect();

            foreach (Sequence s in sequences)
            {
                scrollViewRect.xMin = Mathf.Min(scrollViewRect.xMin, s.nodeRect.xMin);
                scrollViewRect.xMax = Mathf.Max(scrollViewRect.xMax, s.nodeRect.xMax);
                scrollViewRect.yMin = Mathf.Min(scrollViewRect.yMin, s.nodeRect.yMin);
                scrollViewRect.yMax = Mathf.Max(scrollViewRect.yMax, s.nodeRect.yMax);
            }

            // Empty buffer area around edges of scroll rect
            float bufferScale = 0.25f;

            scrollViewRect.xMin -= position.width * bufferScale;
            scrollViewRect.yMin -= position.height * bufferScale;
            scrollViewRect.xMax += position.width * bufferScale;
            scrollViewRect.yMax += position.height * bufferScale;

            // Calc rect for left hand script view
            Rect scriptViewRect = new Rect(0, 0, this.position.width - fungusScript.commandViewWidth, this.position.height);

            // Clip GL drawing so not to overlap scrollbars
            Rect clipRect = new Rect(fungusScript.scriptScrollPos.x + scrollViewRect.x,
                                     fungusScript.scriptScrollPos.y + scrollViewRect.y,
                                     scriptViewRect.width - 15,
                                     scriptViewRect.height - 15);

            GUILayoutUtility.GetRect(scriptViewRect.width, scriptViewRect.height);

            fungusScript.scriptScrollPos = GLDraw.BeginScrollView(scriptViewRect, fungusScript.scriptScrollPos, scrollViewRect, clipRect);

            if (Event.current.type == EventType.ContextClick &&
                clipRect.Contains(Event.current.mousePosition))
            {
                GenericMenu menu     = new GenericMenu();
                Vector2     mousePos = Event.current.mousePosition;
                mousePos += fungusScript.scriptScrollPos;
                menu.AddItem(new GUIContent("Create Sequence"), false, CreateSequenceCallback, mousePos);
                menu.ShowAsContext();

                Event.current.Use();
            }

            BeginWindows();

            GUIStyle windowStyle = new GUIStyle(EditorStyles.toolbarButton);

            windowStyle.stretchHeight = true;
            windowStyle.fixedHeight   = 40;

            windowSequenceMap.Clear();
            for (int i = 0; i < sequences.Length; ++i)
            {
                Sequence sequence = sequences[i];

                float titleWidth  = windowStyle.CalcSize(new GUIContent(sequence.name)).x;
                float windowWidth = Mathf.Max(titleWidth + 10, 100);

                if (fungusScript.selectedSequence == sequence ||
                    fungusScript.executingSequence == sequence)
                {
                    GUI.backgroundColor = Color.green;
                }

                sequence.nodeRect = GUILayout.Window(i, sequence.nodeRect, DrawWindow, "", windowStyle, GUILayout.Width(windowWidth), GUILayout.Height(20), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));

                GUI.backgroundColor = Color.white;

                windowSequenceMap.Add(sequence);
            }

            // Draw connections
            foreach (Sequence s in windowSequenceMap)
            {
                DrawConnections(fungusScript, s, false);
            }
            foreach (Sequence s in windowSequenceMap)
            {
                DrawConnections(fungusScript, s, true);
            }

            EndWindows();

            GLDraw.EndScrollView();
        }
예제 #51
0
        //This is called outside Begin/End Windows from GraphEditor.
        public static void ShowToolbar(Graph graph)
        {
            var owner = graph.agent != null && graph.agent is GraphOwner && (graph.agent as GraphOwner).graph == graph? (GraphOwner)graph.agent : null;

            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);

            ///----------------------------------------------------------------------------------------------
            ///Left side
            ///----------------------------------------------------------------------------------------------

            if (GUILayout.Button("File", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_File(graph, owner).ShowAsContext();
            }

            if (GUILayout.Button("Edit", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_Edit(graph, owner).ShowAsContext();
            }

            if (GUILayout.Button("Prefs", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_Prefs(graph, owner).ShowAsContext();
            }

            GUILayout.Space(10);

            if (owner != null && GUILayout.Button("Select Owner", EditorStyles.toolbarButton, GUILayout.Width(80)))
            {
                Selection.activeObject = owner;
                EditorGUIUtility.PingObject(owner);
            }

            if (EditorUtility.IsPersistent(graph) && GUILayout.Button("Select Graph", EditorStyles.toolbarButton, GUILayout.Width(80)))
            {
                Selection.activeObject = graph;
                EditorGUIUtility.PingObject(graph);
            }

            GUILayout.Space(10);

            if (GUILayout.Button("Open Console", EditorStyles.toolbarButton, GUILayout.Width(90)))
            {
                var type   = ReflectionTools.GetType("NodeCanvas.Editor.GraphConsole");
                var method = type.GetMethod("ShowWindow");
                method.Invoke(null, null);
            }

            ///----------------------------------------------------------------------------------------------
            ///Mid
            ///----------------------------------------------------------------------------------------------

            GUILayout.Space(10);
            GUILayout.FlexibleSpace();

            //TODO: implement search
            // EditorUtils.SearchField(null);

            GUILayout.FlexibleSpace();
            GUILayout.Space(10);

            ///----------------------------------------------------------------------------------------------
            ///Right side
            ///----------------------------------------------------------------------------------------------

            //SL-------------
            //--------------------
            if (EditorUtility.IsPersistent(graph) && GUILayout.Button("ClearUselessNestedAssets", EditorStyles.toolbarButton, GUILayout.Width(175)))
            {
                if (EditorUtility.DisplayDialog("Clear Useless Nested Assets", "清理当前prefab(包括其子物体)或graph资源中无用的嵌套资源,\n\n(需选中物体的是资源目录下的prefab或主Graph Asset).\n\n注意:prefab实例中的嵌套的存盘资源,如果没有被prefab本体引用,同样也被清除 ", "YES", "NO!"))
                {
                    NestedUtility.DeleteAllUselessBoundAsset(graph);
                    e.Use();
                    return;
                }
            }


            GUI.backgroundColor = Color.clear;
            GUI.color           = new Color(1, 1, 1, 0.3f);
            GUILayout.Label(string.Format("{0} @NodeCanvas Framework v{1}", graph.GetType().Name, NodeCanvas.Framework.Internal.GraphSerializationData.FRAMEWORK_VERSION), EditorStyles.toolbarButton);
            GUILayout.Space(10);
            GUI.color           = Color.white;
            GUI.backgroundColor = Color.white;

            //GRAPHOWNER JUMP SELECTION
            if (owner != null)
            {
                if (GUILayout.Button(string.Format("[{0}]", owner.gameObject.name), EditorStyles.toolbarDropDown, GUILayout.Width(120)))
                {
                    var menu = new GenericMenu();
                    foreach (var _o in Object.FindObjectsOfType <GraphOwner>())
                    {
                        var o = _o;
                        menu.AddItem(new GUIContent(o.GetType().Name + "s/" + o.gameObject.name + " --" + o.graph.GetType().Name), false, () => { Selection.activeGameObject = o.gameObject; SetReferences(o); });
                    }
                    menu.ShowAsContext();
                }
            }

            NCPrefs.isLocked = GUILayout.Toggle(NCPrefs.isLocked, "Lock", EditorStyles.toolbarButton);
            GUILayout.EndHorizontal();
            GUI.backgroundColor = Color.white;
            GUI.color           = Color.white;
        }
예제 #52
0
        public override void OnInspectorGUI()
        {
            NewItem _target = (NewItem)target;

            if (target == null)
            {
                return;
            }

            EditorGUILayout.VerticalScope v = new EditorGUILayout.VerticalScope();
            using (v)
            {
                EditorGUI.BeginChangeCheck();
                string name = EditorGUILayout.TextField("Editor name", _target.ItemName);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RegisterCompleteObjectUndo(_target, "Modify Item");
                    _target.ItemName = name;
                    EditorTools.ItemDatabase.RefreshDictionary();
                }
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Attributes", EditorStyles.boldLabel);
                if (GUILayout.Button("+", GUILayout.Width(20)))
                {
                    GenericMenu CreateMenu = new GenericMenu();

                    CreateMenu.AddItem(new GUIContent("Generic"), false, MenuItemCreateAttribute, new object[] { typeof(CommonAttributes) });
                    CreateMenu.AddItem(new GUIContent("Weapons/Stats Attribute"), false, MenuItemCreateAttribute, new object[] { typeof(StatsAttribute) });
                    CreateMenu.AddItem(new GUIContent("Weapons/Weapon Attribute"), false, MenuItemCreateAttribute, new object[] { typeof(WeaponAttribute) });
                    CreateMenu.AddItem(new GUIContent("Weapons/Slot Attribute"), false, MenuItemCreateAttribute, new object[] { typeof(GearSlotAttribute) });
                    CreateMenu.AddItem(new GUIContent("Potion/Recover"), false, MenuItemCreateAttribute, new object[] { typeof(Use_RecoverAttribute) });


                    CreateMenu.ShowAsContext();
                }
                EditorGUILayout.EndHorizontal();

                for (int i = 0; i < _target.attributes.Count; i++)
                {
                    if (!cachedEditors.ContainsKey(_target.attributes[i]))
                    {
                        CacheEditors();
                    }
                }
                EditorGUI.indentLevel++;
                int deleteIndex = -1;
                for (int i = 0; i < _target.attributes.Count; i++)
                {
                    EditorGUILayout.BeginHorizontal();
                    cachedEditors[_target.attributes[i]].OnInspectorGUI();

                    EditorGUI.BeginDisabledGroup(!cachedEditors[_target.attributes[i]].CanDelete() && !Debug);
                    if (GUILayout.Button("X", GUILayout.Width(20)))
                    {
                        deleteIndex = i;
                    }
                    EditorGUI.EndDisabledGroup();
                    EditorGUILayout.EndHorizontal();
                }
                EditorGUI.indentLevel--;
                if (deleteIndex != -1)
                {
                    cachedEditors.Remove(_target.attributes[deleteIndex]);
                    _target.Destroy(_target.attributes[deleteIndex]);
                }
            }
            Event e = Event.current;

            if (e.isMouse && e.button == 1 && v.rect.Contains(e.mousePosition))
            {
                GenericMenu CreateMenu = new GenericMenu();
                CreateMenu.AddItem(new GUIContent("Debug Mode"), Debug, ToggleDebug);
                CreateMenu.AddItem(new GUIContent("Copy"), false, Copy, _target);
                CreateMenu.ShowAsContext();
            }
        }
예제 #53
0
        void IDefinesGenericMenuItems.PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu)
        {
            if (NodePortInfo.Port.ConnectionCount > 0)
            {
                // Remove all connections
                genericMenu.AddSeparator(string.Empty);
                genericMenu.AddItem(new GUIContent("Clear Connections"), false, ClearConnections);
                genericMenu.AddSeparator(string.Empty);

                for (int i = 0; i < NodePortInfo.Port.ConnectionCount; ++i)
                {
                    NodePort connection = NodePortInfo.Port.GetConnection(i);
                    if (connection == null)                       // Connection exists but isn't actually connected
                    {
                        genericMenu.AddItem(new GUIContent("Remove blank connections"), false, RemoveBlankConnections);
                        break;
                    }
                }

                for (int i = 0; i < NodePortInfo.Port.ConnectionCount; ++i)
                {
                    NodePort connection = NodePortInfo.Port.GetConnection(i);
                    if (connection == null)                       // Connection exists but isn't actually connected
                    {
                        continue;
                    }

                    int connectionIndex = i;
                    genericMenu.AddItem(new GUIContent($"Disconnect {connectionIndex} {connection.node.name}:{connection.fieldName}"), false, () => Disconnect(connectionIndex));
                }
            }
        }
예제 #54
0
        ///Pops a menu for animatable properties selection
        public static void ShowAnimatedPropertySelectionMenu(GameObject go, System.Type[] paramTypes, System.Action <MemberInfo, Component> callback)
        {
            var menu = new GenericMenu();

            foreach (var _comp in go.GetComponentsInChildren <Component>(true))
            {
                var comp = _comp;

                if (comp == null)
                {
                    continue;
                }

                var path = AnimationUtility.CalculateTransformPath(comp.transform, go.transform);
                if (comp.gameObject != go)
                {
                    path = "Children/" + path;
                }
                else
                {
                    path = "Self";
                }

                if (comp is Transform)
                {
                    menu.AddItem(new GUIContent(path + "/Transform/Position"), false, () => { callback(typeof(Transform).GetProperty("localPosition"), comp); });
                    menu.AddItem(new GUIContent(path + "/Transform/Rotation"), false, () => { callback(typeof(Transform).GetProperty("localEulerAngles"), comp); });
                    menu.AddItem(new GUIContent(path + "/Transform/Scale"), false, () => { callback(typeof(Transform).GetProperty("localScale"), comp); });
                    continue;
                }

                var type = comp.GetType();
                foreach (var _prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    var prop = _prop;

                    if (!prop.CanRead || !prop.CanWrite)
                    {
                        continue;
                    }

                    if (!paramTypes.Contains(prop.PropertyType))
                    {
                        continue;
                    }

                    var finalPath = string.Format("{0}/{1}/{2}", path, type.Name.SplitCamelCase(), prop.Name.SplitCamelCase());
                    menu.AddItem(new GUIContent(finalPath), false, () => { callback(prop, comp); });
                }

                foreach (var _field in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
                {
                    var field = _field;
                    if (paramTypes.Contains(field.FieldType))
                    {
                        var finalPath = string.Format("{0}/{1}/{2}", path, type.Name.SplitCamelCase(), field.Name.SplitCamelCase());
                        menu.AddItem(new GUIContent(finalPath), false, () => { callback(field, comp); });
                    }
                }
            }

            menu.ShowAsContext();
            Event.current.Use();
        }
예제 #55
0
    private void DrawItem(MenuItem item, Rect groupRect)
    {
        if (item.separator)
        {
            GUI.Box (new Rect (backgroundStyle.contentOffset.x+1, currentItemHeight+1, groupRect.width-2, 1), GUIContent.none, seperator);
            currentItemHeight += 3;
        }
        else
        {
            Rect labelRect = new Rect (backgroundStyle.contentOffset.x, currentItemHeight, groupRect.width, itemHeight);

            bool selected = selectedPath.Contains (item.path);
            if (labelRect.Contains (Event.current.mousePosition))
            {
                selectedPath = item.path;
                selected = true;
            }

            GUI.Label (labelRect, item.content, selected? selectedStyle : itemStyle);

            if (item.group)
            {
                GUI.DrawTexture (new Rect (labelRect.x+labelRect.width-12, labelRect.y+(labelRect.height-12)/2, 12, 12), expandRight);
                if (selected)
                {
                    item.groupPos = new Rect (groupRect.x+groupRect.width+4, groupRect.y+currentItemHeight-2, 0, 0);
                    groupToDraw = item;
                }
            }
            else if (selected && (Event.current.type == EventType.MouseDown || Event.current.button != 1 && Event.current.type == EventType.MouseUp))
            {
                ExecuteMenuItem (item);
                activeMenu = null;
                Event.current.Use ();
            }

            currentItemHeight += itemHeight;
        }
    }
예제 #56
0
        public override void OnInspectorGUI()
        {
            if (GUILayout.Button("ADD"))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Keycodes"), false, AddAxis, -2);
                menu.AddItem(new GUIContent("Mouse/Horizontal"), false, AddAxis, 1);
                menu.AddItem(new GUIContent("Mouse/Vertical"), false, AddAxis, 0);
                menu.AddItem(new GUIContent("Mouse/Wheel"), false, AddAxis, 2);
                menu.AddItem(new GUIContent("Joystick/Left Horizontal"), false, AddAxis, 3);
                menu.AddItem(new GUIContent("Joystick/Left Vertical"), false, AddAxis, 4);
                menu.AddItem(new GUIContent("Joystick/Right Horizontal"), false, AddAxis, 5);
                menu.AddItem(new GUIContent("Joystick/Right Vertical"), false, AddAxis, 6);
                menu.AddItem(new GUIContent("Custom Axis"), false, AddAxis, -1);
                menu.ShowAsContext();
            }

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Key Axes", EditorStyles.boldLabel);


            for (int i = 0; i < _keyAxes.arraySize; i++)
            {
                SerializedProperty child = _keyAxes.GetArrayElementAtIndex(i);

                string label = _axis.keyAxes[i].ToString();
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.PropertyField(child, new GUIContent(label), true);

                if (GUILayout.Button("X", GUILayout.Width(18), GUILayout.Height(18)))
                {
                    _axis.keyAxes.RemoveAt(i);
                    UpdateObject();
                    return;
                }

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Space();
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Non-Key Axes", EditorStyles.boldLabel);

            for (int i = 0; i < _nativeAxes.arraySize; i++)
            {
                SerializedProperty child = _nativeAxes.GetArrayElementAtIndex(i);

                string label = _axis.nativeAxes[i].GetEditorLabelName();
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.PropertyField(child, new GUIContent(label), true);

                if (GUILayout.Button("X", GUILayout.Width(18), GUILayout.Height(18)))
                {
                    _axis.nativeAxes.RemoveAt(i);
                    UpdateObject();
                    return;
                }

                EditorGUILayout.EndHorizontal();


                string axisName = _axis.nativeAxes[i].GetAxisName();
                try
                {
                    UnityEngine.Input.GetAxis(axisName);
                }
                catch
                {
                    EditorGUILayout.HelpBox("Vous devez avoir un axe nommé " + axisName + " dans l'input natif de unity.", MessageType.Error);
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
예제 #57
0
    private void DrawToolbarGUI()
    {
        GUILayout.BeginHorizontal(EditorStyles.toolbar);

        if (OnlineMapsUpdater.hasNewVersion && updateAvailableContent != null)
        {
            Color defBackgroundColor = GUI.backgroundColor;
            GUI.backgroundColor = new Color(1, 0.5f, 0.5f);
            if (GUILayout.Button(updateAvailableContent, EditorStyles.toolbarButton))
            {
                OnlineMapsUpdater.OpenWindow();
            }
            GUI.backgroundColor = defBackgroundColor;
        }
        else GUILayout.Label("");

        if (GUILayout.Button("Help", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
        {
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("Documentation"), false, OnViewDocs);
            menu.AddItem(new GUIContent("API Reference"), false, OnViewAPI);
            menu.AddItem(new GUIContent("Atlas of Examples"), false, OnViewAtlas);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Product Page"), false, OnProductPage);
            menu.AddItem(new GUIContent("Forum"), false, OnViewForum);
            menu.AddItem(new GUIContent("Check Updates"), false, OnCheckUpdates);
            menu.AddItem(new GUIContent("Support"), false, OnSendMail);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("About"), false, OnAbout);
            menu.ShowAsContext();
        }

        GUILayout.EndHorizontal();
    }
예제 #58
0
        void OnGUI()
        {
            if (m_Settings == null)
            {
                return;
            }

            if (m_IsResizingVerticalSplitter)
            {
                m_VerticalSplitterRatio = Mathf.Clamp(Event.current.mousePosition.y / position.height, 0.2f, 0.9f);
            }

            if (m_IsResizingHorizontalSplitter)
            {
                m_HorizontalSplitterRatio = Mathf.Clamp(Event.current.mousePosition.x / position.width, 0.15f, 0.6f);
            }

            var toolbarRect  = new Rect(0, 0, position.width, position.height);
            var servicesRect = new Rect(0, k_ToolbarHeight, (position.width * m_HorizontalSplitterRatio), position.height);
            var itemRect     = new Rect(servicesRect.width + k_SplitterThickness, k_ToolbarHeight, position.width - servicesRect.width - k_SplitterThickness, (position.height * m_VerticalSplitterRatio) - k_ToolbarHeight);
            var logRect      = new Rect(servicesRect.width + k_SplitterThickness, k_ToolbarHeight + itemRect.height + k_SplitterThickness, position.width - servicesRect.width - k_SplitterThickness,
                                        position.height - itemRect.height - k_SplitterThickness);
            var verticalSplitterRect   = new Rect(servicesRect.width + k_SplitterThickness, k_ToolbarHeight + itemRect.height, position.width, k_SplitterThickness);
            var horizontalSplitterRect = new Rect(servicesRect.width, k_ToolbarHeight, k_SplitterThickness, position.height - k_ToolbarHeight);


            //EditorGUI.LabelField(splitterRect, string.Empty, UnityEngine.GUI.skin.horizontalSlider);
            EditorGUIUtility.AddCursorRect(verticalSplitterRect, MouseCursor.ResizeVertical);
            EditorGUIUtility.AddCursorRect(horizontalSplitterRect, MouseCursor.ResizeHorizontal);
            if (Event.current.type == EventType.MouseDown && verticalSplitterRect.Contains(Event.current.mousePosition))
            {
                m_IsResizingVerticalSplitter = true;
            }
            else if (Event.current.type == EventType.MouseDown && horizontalSplitterRect.Contains(Event.current.mousePosition))
            {
                m_IsResizingHorizontalSplitter = true;
            }
            else if (Event.current.type == EventType.MouseUp)
            {
                m_IsResizingVerticalSplitter   = false;
                m_IsResizingHorizontalSplitter = false;
            }

            GUILayout.BeginArea(toolbarRect);
            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            {
                var  guiMode = new GUIContent("Create");
                Rect rMode   = GUILayoutUtility.GetRect(guiMode, EditorStyles.toolbarDropDown);
                if (EditorGUI.DropdownButton(rMode, guiMode, FocusType.Passive, EditorStyles.toolbarDropDown))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Local Hosting"), false, () => AddService(0, "Local Hosting"));
                    menu.AddItem(new GUIContent("Custom Service"), false, () => GetWindow <HostingServicesAddServiceWindow>(true, "Custom Service").Initialize(m_Settings));
                    menu.DropDown(rMode);
                }
                GUILayout.FlexibleSpace();
            }
            GUILayout.EndHorizontal();
            GUILayout.EndArea();


            DrawOutline(servicesRect, 1);

            GUILayout.BeginArea(servicesRect);
            {
                Rect r = new Rect(servicesRect);
                r.y = 0;
                DrawServicesList(r);
            }
            GUILayout.EndArea();

            DrawOutline(itemRect, 1);
            GUILayout.BeginArea(itemRect, m_ItemRectPadding);
            {
                EditorGUILayout.Space();
                DrawServicesArea();
                EditorGUILayout.Space();
            }
            GUILayout.EndArea();

            DrawOutline(logRect, 1);
            GUILayout.BeginArea(logRect, m_LogRectPadding);
            {
                DrawLogArea(logRect);
            }
            GUILayout.EndArea();

            if (m_IsResizingVerticalSplitter || m_IsResizingHorizontalSplitter)
            {
                Repaint();
            }
        }
예제 #59
0
    private bool BakeButton(params GUILayoutOption[] options)
    {
        GUIContent content = new GUIContent (ObjectNames.NicifyVariableName (bakeMode.ToString ()));

        Rect dropdownRect = GUILayoutUtility.GetRect (content, (GUIStyle)"DropDownButton", options);
        Rect buttonRect = dropdownRect;
        buttonRect.xMin = buttonRect.xMax - 20;
        if (Event.current.type != EventType.MouseDown || !buttonRect.Contains (Event.current.mousePosition))
            return GUI.Button (dropdownRect, content, (GUIStyle)"DropDownButton");
        GenericMenu genericMenu = new GenericMenu ();
        string[] names = Enum.GetNames (typeof(BakeMode));
        int num1 = Array.IndexOf<string> (names, Enum.GetName (typeof(BakeMode), this.bakeMode));
        int num2 = 0;
        foreach (string text in Enumerable.Select<string, string> (names, x => ObjectNames.NicifyVariableName(x))) {
            genericMenu.AddItem (new GUIContent (text), num2 == num1, new GenericMenu.MenuFunction2 (this.BakeDropDownCallback), num2++);
        }
        genericMenu.DropDown (dropdownRect);
        Event.current.Use ();
        return false;
    }
예제 #60
0
        //private bool PathExists(string path, string parent)
        //{
        //    if (path.IsNullOrWhitespace())
        //    {
        //        return false;
        //    }

        //    if (parent.IsNullOrWhitespace() == false)
        //    {
        //        path = Path.Combine(parent, path);
        //    }

        //    return File.Exists(path);
        //}

        void IDefinesGenericMenuItems.PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu)
        {
            var parentProperty = property.FindParent(p => p.Info.HasSingleBackingMember, true);
            IPropertyValueEntry <string> entry = (IPropertyValueEntry <string>)property.ValueEntry;
            string parent = this.parent.GetString(parentProperty);

            if (genericMenu.GetItemCount() > 0)
            {
                genericMenu.AddSeparator("");
            }

            string path = entry.SmartValue;

            // Create an absolute path from the current value.
            if (path.IsNullOrWhitespace() == false)
            {
                if (Path.IsPathRooted(path) == false)
                {
                    if (parent.IsNullOrWhitespace() == false)
                    {
                        path = Path.Combine(parent, path);
                    }

                    path = Path.GetFullPath(path);
                }
            }
            else if (parent.IsNullOrWhitespace() == false)
            {
                // Use the parent path instead.
                path = Path.GetFullPath(parent);
            }
            else
            {
                // Default to Unity project.
                path = Path.GetDirectoryName(Application.dataPath);
            }

            // Find first existing directory.
            if (path.IsNullOrWhitespace() == false)
            {
                while (path.IsNullOrWhitespace() == false && Directory.Exists(path) == false)
                {
                    path = Path.GetDirectoryName(path);
                }
            }

            // Show in explorer
            if (path.IsNullOrWhitespace() == false)
            {
                genericMenu.AddItem(new GUIContent("Show in explorer"), false, () => System.Diagnostics.Process.Start(path));
            }
            else
            {
                genericMenu.AddDisabledItem(new GUIContent("Show in explorer"));
            }
        }