private void DrawRendererFeature(int index, ref SerializedProperty renderFeatureProperty) { Object rendererFeatureObjRef = renderFeatureProperty.objectReferenceValue; if (rendererFeatureObjRef != null) { bool hasChangedProperties = false; string title = ObjectNames.GetInspectorTitle(rendererFeatureObjRef); // Get the serialized object for the editor script & update it Editor rendererFeatureEditor = m_Editors[index]; SerializedObject serializedRendererFeaturesEditor = rendererFeatureEditor.serializedObject; serializedRendererFeaturesEditor.Update(); // Foldout header EditorGUI.BeginChangeCheck(); SerializedProperty activeProperty = serializedRendererFeaturesEditor.FindProperty("m_Active"); bool displayContent = CoreEditorUtils.DrawHeaderToggle(title, renderFeatureProperty, activeProperty, pos => OnContextClick(pos, index)); hasChangedProperties |= EditorGUI.EndChangeCheck(); // ObjectEditor if (displayContent) { EditorGUI.BeginChangeCheck(); SerializedProperty nameProperty = serializedRendererFeaturesEditor.FindProperty("m_Name"); nameProperty.stringValue = ValidateName(EditorGUILayout.DelayedTextField(Styles.PassNameField, nameProperty.stringValue)); if (EditorGUI.EndChangeCheck()) { hasChangedProperties = true; // We need to update sub-asset name rendererFeatureObjRef.name = nameProperty.stringValue; AssetDatabase.SaveAssets(); // Triggers update for sub-asset name change ProjectWindowUtil.ShowCreatedAsset(target); } EditorGUI.BeginChangeCheck(); rendererFeatureEditor.OnInspectorGUI(); hasChangedProperties |= EditorGUI.EndChangeCheck(); EditorGUILayout.Space(EditorGUIUtility.singleLineHeight); } // Apply changes and save if the user has modified any settings if (hasChangedProperties) { serializedRendererFeaturesEditor.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties(); ForceSave(); } } else { CoreEditorUtils.DrawHeaderToggle(Styles.MissingFeature, renderFeatureProperty, m_FalseBool, pos => OnContextClick(pos, index)); m_FalseBool.boolValue = false; // always make sure false bool is false EditorGUILayout.HelpBox(Styles.MissingFeature.tooltip, MessageType.Error); if (GUILayout.Button("Attempt Fix", EditorStyles.miniButton)) { ScriptableRendererData data = target as ScriptableRendererData; data.ValidateRendererFeatures(); } } }
// Convert all inlets/outlets into node slots. void PopulateSlots() { // Enumeration flags: all public and non-public members const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; // Inlets (property) foreach (var prop in _runtimeInstance.GetType().GetProperties(flags)) { // Check if it has an inlet attribute. var attrs = prop.GetCustomAttributes(typeof(Wiring.InletAttribute), true); if (attrs.Length == 0) { continue; } // Register the setter method as an input slot. var slot = AddInputSlot("set_" + prop.Name, prop.PropertyType); // Apply the standard nicifying rule. slot.title = ObjectNames.NicifyVariableName(prop.Name); } // Inlets (method) foreach (var method in _runtimeInstance.GetType().GetMethods(flags)) { // Check if it has an inlet attribute. var attrs = method.GetCustomAttributes(typeof(Wiring.InletAttribute), true); if (attrs.Length == 0) { continue; } // Register the method as an input slot. var args = method.GetParameters(); var dataType = args.Length > 0 ? args[0].ParameterType : null; var slot = AddInputSlot(method.Name, dataType); // Apply the standard nicifying rule. slot.title = ObjectNames.NicifyVariableName(method.Name); } // Outlets (UnityEvent members) foreach (var field in _runtimeInstance.GetType().GetFields(flags)) { // Check if it has an outlet attribute. var attrs = field.GetCustomAttributes(typeof(Wiring.OutletAttribute), true); if (attrs.Length == 0) { continue; } // Register it as an output slot. var dataType = ConnectionTools.GetEventDataType(field.FieldType); var slot = AddOutputSlot(field.Name, dataType); // Apply the standard nicifying rule and remove tailing "Event". var title = ObjectNames.NicifyVariableName(field.Name); if (title.EndsWith(" Event")) { title = title.Substring(0, title.Length - 6); } slot.title = title; } }
private static string NicifyTypeName(Type type) { return(ObjectNames.NicifyVariableName(type.Name)); }
public override void OnImportAsset(AssetImportContext ctx) { string sceneName = null; GameObject gltfScene = null; UnityEngine.Mesh[] meshes = null; try { sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath); gltfScene = CreateGLTFScene(ctx.assetPath); // Remove empty roots if (_removeEmptyRootObjects) { var t = gltfScene.transform; while ( gltfScene.transform.childCount == 1 && gltfScene.GetComponents <Component>().Length == 1) { var parent = gltfScene; gltfScene = gltfScene.transform.GetChild(0).gameObject; t = gltfScene.transform; t.parent = null; // To keep transform information in the new parent Object.DestroyImmediate(parent); // Get rid of the parent } } // Ensure there are no hide flags present (will cause problems when saving) gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave); foreach (Transform child in gltfScene.transform) { child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave); } // Zero position gltfScene.transform.position = Vector3.zero; // Get meshes var meshNames = new List <string>(); var meshHash = new HashSet <UnityEngine.Mesh>(); var meshFilters = gltfScene.GetComponentsInChildren <MeshFilter>(); var vertexBuffer = new List <Vector3>(); meshes = meshFilters.Select(mf => { var mesh = mf.sharedMesh; vertexBuffer.Clear(); mesh.GetVertices(vertexBuffer); for (var i = 0; i < vertexBuffer.Count; ++i) { vertexBuffer[i] *= _scaleFactor; } mesh.SetVertices(vertexBuffer); if (_swapUvs) { var uv = mesh.uv; var uv2 = mesh.uv2; mesh.uv = uv2; mesh.uv2 = uv2; } if (_importNormals == GLTFImporterNormals.None) { mesh.normals = new Vector3[0]; } if (_importNormals == GLTFImporterNormals.Calculate) { mesh.RecalculateNormals(); } mesh.UploadMeshData(!_readWriteEnabled); if (_generateColliders) { var collider = mf.gameObject.AddComponent <MeshCollider>(); collider.sharedMesh = mesh; } if (meshHash.Add(mesh)) { var meshName = string.IsNullOrEmpty(mesh.name) ? mf.gameObject.name : mesh.name; mesh.name = ObjectNames.GetUniqueName(meshNames.ToArray(), meshName); meshNames.Add(mesh.name); } return(mesh); }).ToArray(); var renderers = gltfScene.GetComponentsInChildren <Renderer>(); if (_importMaterials) { // Get materials var materialNames = new List <string>(); var materialHash = new HashSet <UnityEngine.Material>(); var materials = renderers.SelectMany(r => { return(r.sharedMaterials.Select(mat => { if (materialHash.Add(mat)) { var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name; if (matName == mat.shader.name) { matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/") + 1, matName.Length - 1)); } // Ensure name is unique matName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(matName)); matName = ObjectNames.GetUniqueName(materialNames.ToArray(), matName); mat.name = matName; materialNames.Add(matName); } return mat; })); }).ToArray(); // Get textures var textureNames = new List <string>(); var textureHash = new HashSet <Texture2D>(); var texMaterialMap = new Dictionary <Texture2D, List <TexMaterialMap> >(); var textures = materials.SelectMany(mat => { var shader = mat.shader; if (!shader) { return(Enumerable.Empty <Texture2D>()); } var matTextures = new List <Texture2D>(); for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i) { if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { var propertyName = ShaderUtil.GetPropertyName(shader, i); var tex = mat.GetTexture(propertyName) as Texture2D; if (tex) { if (textureHash.Add(tex)) { var texName = tex.name; if (string.IsNullOrEmpty(texName)) { if (propertyName.StartsWith("_")) { texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1)); } } // Ensure name is unique texName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(texName)); texName = ObjectNames.GetUniqueName(textureNames.ToArray(), texName); tex.name = texName; textureNames.Add(texName); matTextures.Add(tex); } List <TexMaterialMap> materialMaps; if (!texMaterialMap.TryGetValue(tex, out materialMaps)) { materialMaps = new List <TexMaterialMap>(); texMaterialMap.Add(tex, materialMaps); } materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap")); } } } return(matTextures); }).ToArray(); var folderName = Path.GetDirectoryName(ctx.assetPath); // Save textures as separate assets and rewrite refs // TODO: Support for other texture types if (textures.Length > 0) { var texturesRoot = string.Concat(folderName, "/", "Textures/"); Directory.CreateDirectory(texturesRoot); foreach (var tex in textures) { var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); File.WriteAllBytes(texPath, _useJpgTextures ? tex.EncodeToJPG() : tex.EncodeToPNG()); AssetDatabase.ImportAsset(texPath); } } // Save materials as separate assets and rewrite refs if (materials.Length > 0) { var materialRoot = string.Concat(folderName, "/", "Materials/"); Directory.CreateDirectory(materialRoot); foreach (var mat in materials) { var materialPath = string.Concat(materialRoot, mat.name, ".mat"); var newMat = mat; CopyOrNew(mat, materialPath, m => { // Fix references newMat = m; foreach (var r in renderers) { var sharedMaterials = r.sharedMaterials; for (var i = 0; i < sharedMaterials.Length; ++i) { var sharedMaterial = sharedMaterials[i]; if (sharedMaterial.name == mat.name) { sharedMaterials[i] = m; } } sharedMaterials = sharedMaterials.Where(sm => sm).ToArray(); r.sharedMaterials = sharedMaterials; } }); // Fix textures // HACK: This needs to be a delayed call. // Unity needs a frame to kick off the texture import so we can rewrite the ref if (textures.Length > 0) { EditorApplication.delayCall += () => { for (var i = 0; i < textures.Length; ++i) { var tex = textures[i]; var texturesRoot = string.Concat(folderName, "/", "Textures/"); var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); // Grab new imported texture var materialMaps = texMaterialMap[tex]; var importer = (TextureImporter)TextureImporter.GetAtPath(texPath); var importedTex = AssetDatabase.LoadAssetAtPath <Texture2D>(texPath); if (importer != null) { var isNormalMap = false; foreach (var materialMap in materialMaps) { if (materialMap.Material == mat) { isNormalMap |= materialMap.IsNormalMap; newMat.SetTexture(materialMap.Property, importedTex); } } ; if (isNormalMap) { // Try to auto-detect normal maps importer.textureType = TextureImporterType.NormalMap; } else if (importer.textureType == TextureImporterType.Sprite) { // Force disable sprite mode, even for 2D projects importer.textureType = TextureImporterType.Default; } importer.SaveAndReimport(); } else { Debug.LogWarning(string.Format("GLTFImporter: Unable to import texture at path: {0}", texPath)); } } }; } } } } else { var temp = GameObject.CreatePrimitive(PrimitiveType.Plane); temp.SetActive(false); var defaultMat = new[] { temp.GetComponent <Renderer>().sharedMaterial }; DestroyImmediate(temp); foreach (var rend in renderers) { rend.sharedMaterials = defaultMat; } } } catch { if (gltfScene) { DestroyImmediate(gltfScene); } throw; } #if UNITY_2017_3_OR_NEWER // Set main asset ctx.AddObjectToAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddObjectToAsset("mesh " + mesh.name, mesh); } ctx.SetMainObject(gltfScene); #else // Set main asset ctx.SetMainAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddSubAsset("mesh " + mesh.name, mesh); } #endif }
protected void RefreshBindingOptions() { var actionReference = (InputActionReference)m_ActionProperty.objectReferenceValue; var action = actionReference?.action; if (action == null) { m_BindingOptions = new GUIContent[0]; m_BindingOptionValues = new string[0]; m_SelectedBindingOption = -1; return; } var bindings = action.bindings; var bindingCount = bindings.Count; m_BindingOptions = new GUIContent[bindingCount]; m_BindingOptionValues = new string[bindingCount]; m_SelectedBindingOption = -1; var currentBindingId = m_BindingIdProperty.stringValue; for (var i = 0; i < bindingCount; ++i) { var binding = bindings[i]; var bindingId = binding.id.ToString(); var haveBindingGroups = !string.IsNullOrEmpty(binding.groups); // If we don't have a binding groups (control schemes), show the device that if there are, for example, // there are two bindings with the display string "A", the user can see that one is for the keyboard // and the other for the gamepad. var displayOptions = InputBinding.DisplayStringOptions.DontUseShortDisplayNames | InputBinding.DisplayStringOptions.IgnoreBindingOverrides; if (!haveBindingGroups) { displayOptions |= InputBinding.DisplayStringOptions.DontOmitDevice; } // Create display string. var displayString = action.GetBindingDisplayString(i, displayOptions); // If binding is part of a composite, include the part name. if (binding.isPartOfComposite) { displayString = $"{ObjectNames.NicifyVariableName(binding.name)}: {displayString}"; } // Some composites use '/' as a separator. When used in popup, this will lead to to submenus. Prevent // by instead using a backlash. displayString = displayString.Replace('/', '\\'); // If the binding is part of control schemes, mention them. if (haveBindingGroups) { var asset = action.actionMap?.asset; if (asset != null) { var controlSchemes = string.Join(", ", binding.groups.Split(InputBinding.Separator) .Select(x => asset.controlSchemes.FirstOrDefault(c => c.bindingGroup == x).name)); displayString = $"{displayString} ({controlSchemes})"; } } m_BindingOptions[i] = new GUIContent(displayString); m_BindingOptionValues[i] = bindingId; if (currentBindingId == bindingId) { m_SelectedBindingOption = i; } } }
internal static void AddTimeAreaMenuItems(GenericMenu menu, WindowState state) { foreach (var value in Enum.GetValues(typeof(TimelineAsset.DurationMode))) { var mode = (TimelineAsset.DurationMode)value; var item = EditorGUIUtility.TextContent(string.Format(TimelineWindow.Styles.DurationModeText, L10n.Tr(ObjectNames.NicifyVariableName(mode.ToString())))); if (state.recording || state.IsEditingASubTimeline() || state.editSequence.asset == null || state.editSequence.isReadOnly) { menu.AddDisabledItem(item); } else { menu.AddItem(item, state.editSequence.asset.durationMode == mode, () => SelectDurationCallback(state, mode)); } menu.AddItem(DirectorStyles.showMarkersOnTimeline, state.showMarkerHeader, () => Action.InvokeWithSelected <ToggleShowMarkersOnTimeline>()); } }
private static void DoBoneRender(Transform transform, Transform childTransform, BoneShape shape, Color color, float size) { Vector3 start = transform.position; Vector3 end = childTransform != null ? childTransform.position : start; GameObject boneGO = transform.gameObject; float length = (end - start).magnitude; bool tipBone = (length < k_Epsilon); int id = GUIUtility.GetControlID(s_ButtonHash, FocusType.Passive); Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.Layout: { HandleUtility.AddControl(id, tipBone ? HandleUtility.DistanceToCircle(start, k_BoneTipSize * size * 0.5f) : HandleUtility.DistanceToLine(start, end)); break; } case EventType.MouseMove: if (id == HandleUtility.nearestControl) { HandleUtility.Repaint(); } break; case EventType.MouseDown: { if (HandleUtility.nearestControl == id && evt.button == 0) { if (!SceneVisibilityManager.instance.IsPickingDisabled(boneGO, false)) { GUIUtility.hotControl = id; // Grab mouse focus EditorHelper.HandleClickSelection(boneGO, evt); evt.Use(); } } break; } case EventType.MouseDrag: { if (!evt.alt && GUIUtility.hotControl == id) { if (!SceneVisibilityManager.instance.IsPickingDisabled(boneGO, false)) { DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = new UnityEngine.Object[] { transform }; DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(transform)); GUIUtility.hotControl = 0; evt.Use(); } } break; } case EventType.MouseUp: { if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) { GUIUtility.hotControl = 0; evt.Use(); } break; } case EventType.Repaint: { Color highlight = color; bool hoveringBone = GUIUtility.hotControl == 0 && HandleUtility.nearestControl == id; hoveringBone = hoveringBone && !SceneVisibilityManager.instance.IsPickingDisabled(transform.gameObject, false); if (hoveringBone) { highlight = Handles.preselectionColor; } else if (Selection.Contains(boneGO) || Selection.activeObject == boneGO) { highlight = Handles.selectedColor; } if (tipBone) { Handles.color = highlight; Handles.SphereHandleCap(0, start, Quaternion.identity, k_BoneTipSize * size, EventType.Repaint); } else if (shape == BoneShape.Line) { Handles.color = highlight; Handles.DrawLine(start, end); } else { if (shape == BoneShape.Pyramid) { pyramidMeshRenderer.AddInstance(ComputeBoneMatrix(start, end, length, size), color, highlight); } else // if (shape == BoneShape.Box) { boxMeshRenderer.AddInstance(ComputeBoneMatrix(start, end, length, size), color, highlight); } } } break; } }
void DoCustomEffectSorter() { EditorUtilities.DrawSplitter(); m_ShowCustomSorter.boolValue = EditorUtilities.DrawHeader("Custom Effect Sorting", m_ShowCustomSorter.boolValue); if (m_ShowCustomSorter.boolValue) { bool isInPrefab = false; // Init lists if needed if (m_CustomLists == null) { // In some cases the editor will refresh before components which means // components might not have been fully initialized yet. In this case we also // need to make sure that we're not in a prefab as sorteBundles isn't a // serializable object and won't exist until put on a scene. if (m_Target.sortedBundles == null) { isInPrefab = string.IsNullOrEmpty(m_Target.gameObject.scene.name); if (!isInPrefab) { // sortedBundles will be initialized and ready to use on the next frame Repaint(); } } else { // Create a reorderable list for each injection event m_CustomLists = new Dictionary <PostProcessEvent, ReorderableList>(); foreach (var evt in Enum.GetValues(typeof(PostProcessEvent)).Cast <PostProcessEvent>()) { var bundles = m_Target.sortedBundles[evt]; var listName = ObjectNames.NicifyVariableName(evt.ToString()); var list = new ReorderableList(bundles, typeof(SerializedBundleRef), true, true, false, false); list.drawHeaderCallback = (rect) => { EditorGUI.LabelField(rect, listName); }; list.drawElementCallback = (rect, index, isActive, isFocused) => { var sbr = (SerializedBundleRef)list.list[index]; EditorGUI.LabelField(rect, sbr.bundle.attribute.menuItem); }; list.onReorderCallback = (l) => { EditorUtility.SetDirty(m_Target); }; m_CustomLists.Add(evt, list); } } } GUILayout.Space(5); if (isInPrefab) { EditorGUILayout.HelpBox("Not supported in prefabs.", MessageType.Info); GUILayout.Space(3); return; } bool anyList = false; if (m_CustomLists != null) { foreach (var kvp in m_CustomLists) { var list = kvp.Value; // Skip empty lists to avoid polluting the inspector if (list.count == 0) { continue; } list.DoLayoutList(); anyList = true; } } if (!anyList) { EditorGUILayout.HelpBox("No custom effect loaded.", MessageType.Info); GUILayout.Space(3); } } }
private Element BuildElements() { Element root = new Element(ObjectNames.NicifyVariableName(this.m_Type.Name), ""); Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type => (IsAssignableToGenericType(type, this.m_Type) || this.m_Type.IsAssignableFrom(type)) && !type.IsAbstract && !type.HasAttribute(typeof(ExcludeFromCreation))).ToArray(); // Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(c => c.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == this.m_Type)).ToArray(); types = types.OrderBy(x => x.BaseType.Name).ToArray(); foreach (Type type in types) { ComponentMenu attribute = type.GetCustomAttribute <ComponentMenu>(); string menu = attribute != null ? attribute.componentMenu : string.Empty; if (string.IsNullOrEmpty(menu)) { Element element = new Element(ObjectNames.NicifyVariableName(type.Name), menu); element.type = type; element.parent = root; root.children.Add(element); } menu = menu.Replace("/", "."); string[] s = menu.Split('.'); Element prev = null; string cur = string.Empty; for (int i = 0; i < s.Length - 1; i++) { cur += (string.IsNullOrEmpty(cur) ? "" : ".") + s[i]; Element parent = root.Find(cur); if (parent == null) { parent = new Element(s[i], cur); if (prev != null) { parent.parent = prev; prev.children.Add(parent); } else { parent.parent = root; root.children.Add(parent); } } prev = parent; } if (prev != null) { Element element = new Element(ObjectNames.NicifyVariableName(type.Name), menu); element.type = type; element.parent = prev; prev.children.Add(element); } } root.children = root.children.OrderByDescending(x => x.children.Count).ToList(); Element newScript = new Element("New script", ""); newScript.parent = root; Element script = new Element(ObjectNames.NicifyVariableName(this.m_Type.Name), "New script." + ObjectNames.NicifyVariableName(this.m_Type.Name)); script.parent = newScript; script.type = this.m_Type; script.onGUI = delegate() { GUILayout.Label("Name"); GUI.SetNextControlName("AddAssetNewScript"); this.m_NewScriptName = GUILayout.TextField(this.m_NewScriptName); GUI.FocusControl("AddAssetNewScript"); GUILayout.FlexibleSpace(); EditorGUI.BeginDisabledGroup(onCreateCallback == null || string.IsNullOrEmpty(this.m_NewScriptName)); if (GUILayout.Button("Create and add") || Event.current.keyCode == KeyCode.Return) { onCreateCallback(this.m_NewScriptName); Close(); } EditorGUI.EndDisabledGroup(); }; newScript.children.Add(script); root.children.Add(newScript); return(root); }
static PlayerSettingsOverridePropertyDrawer() { _knownPlayerSettings = BuildSettings.GetOverridablePlayerSettings().ToArray(); _knownPlayerSettingPropNames = (from info in _knownPlayerSettings select info.Name).ToArray(); _knownPlayerSettingPropNamesPretty = (from info in _knownPlayerSettings select new GUIContent(ObjectNames.NicifyVariableName(info.Name))).ToArray(); }
void OnModuleWindowSlotGUI(CGModule module) { int i = 0; float h = 18; while (module.Input.Count > i || module.Output.Count > i) { float y = CurvyStyles.ModuleWindowTitleHeight + h * i; GUILayout.BeginHorizontal(); if (module.Input.Count > i) { CGModuleInputSlot slot = module.Input[i]; Color slotColor = getTypeColor(slot.Info.DataTypes); if (Canvas.IsLinkDrag && !slot.IsValidTarget(Canvas.LinkDragFrom)) { slotColor = new Color(0.2f, 0.2f, 0.2f).SkinAwareColor(true); } DTGUI.PushColor(slotColor); GUILayout.Box("<", CurvyStyles.Slot); DTGUI.PopColor(); string postfix = ""; if (slot.Info.Array) { postfix = (slot.LastDataCountINTERNAL > 0) ? "[" + slot.LastDataCountINTERNAL.ToString() + "]" : "[]"; } GUILayout.Label(new GUIContent(ObjectNames.NicifyVariableName(slot.Info.Name) + postfix, slot.Info.Tooltip), CurvyStyles.GetSlotLabelStyle(slot)); slot.DropZone = new Rect(0, y, module.Properties.Dimensions.width / 2, h); slot.Origin = new Vector2(module.Properties.Dimensions.xMin, module.Properties.Dimensions.yMin + y + h / 2); // LinkDrag? if (Canvas.IsLinkDrag) { // If ending drag over dropzone, create static link if (EV.type == EventType.MouseUp && slot.DropZone.Contains(EV.mousePosition) && slot.IsValidTarget(Canvas.LinkDragFrom)) { finishLink(slot); } } // Clicking on Dropzone to pick existing link else if (LMB && slot.Count == 1 && slot.DropZone.Contains(EV.mousePosition)) { var linkedOutSlot = slot.SourceSlot(); linkedOutSlot.UnlinkFrom(slot); EditorUtility.SetDirty(slot.Module); startLinkDrag(linkedOutSlot); GUIUtility.ExitGUI(); } } if (module.Output.Count > i) { CGModuleOutputSlot slot = module.Output[i]; string postfix = ""; if (slot.Info.Array) { postfix = (slot.Data != null && slot.Data.Length > 1) ? "[" + slot.Data.Length.ToString() + "]" : ""; } GUILayout.Label(new GUIContent(ObjectNames.NicifyVariableName(slot.Info.Name) + postfix, slot.Info.Tooltip), CurvyStyles.GetSlotLabelStyle(slot)); DTGUI.PushColor(getTypeColor(slot.Info.DataTypes)); GUILayout.Box(">", CurvyStyles.Slot); DTGUI.PopColor(); // Debug /* * if (Generator.ShowDebug) * { * GUI.enabled = slot.Data != null && slot.Data.Length>0; * if (GUILayout.Button(new GUIContent(CurvyStyles.DebugTexture, "Show Dump"), CurvyStyles.SmallButton, GUILayout.Width(16), GUILayout.Height(16))) * DTDebugWindow.Open(slot.Data[0].GetType().Name + ":", slot.Data[0].ToDumpString()); * GUI.enabled = true; * } */ slot.DropZone = new Rect(module.Properties.Dimensions.width / 2, y, module.Properties.Dimensions.width / 2, h); slot.Origin = new Vector2(module.Properties.Dimensions.xMax, module.Properties.Dimensions.yMin + y + h / 2); // Start Linking? if (LMB && !Canvas.IsSelectionRectDrag && slot.DropZone.Contains(EV.mousePosition)) { startLinkDrag(slot); } } GUILayout.EndHorizontal(); i++; } }
private void DisplayOneItem(Object toDisplay, string nameInListPath, int index, float width, bool disable) { if (toDisplay == null && string.IsNullOrEmpty(nameInListPath)) { return; } if (toDisplay == null && !UnityEssentialsPreferences.GetBool(UnityEssentialsPreferences.SHOW_GAMEOBJECTS_FROM_OTHER_SCENE, true)) { return; } GUI.color = (PeekSerializeObject.LastSelectedObject == toDisplay && toDisplay != null) ? Color.green : Color.white; EditorGUI.BeginDisabledGroup(disable); { using (HorizontalScope horizontalScope = new HorizontalScope(GUILayout.Width(width), GUILayout.Height(_heightLine))) { float widthExtent = CalculateWidthExtentOptions.CalculateWidthExtent(width, index, ListToDisplay.arraySize); float widthButtonWithoutExtent = CalculateWidthExtentOptions.CalculateButtonWidthWithoutExtent(widthExtent, _heightLine, _margin); if (_calculateExtent) { GUILayout.Label("", GUILayout.Width(widthExtent), GUILayout.Height(_heightLine)); } //display bookmark button bool clicOnBookMark = BookMarkButtonOptions.ButtonImageWithHover(WIDTH_BUTTON_HOVER, toDisplay != null, _heightLine); if (clicOnBookMark) { OnBookMarkClic?.Invoke(index); return; } //display main logo DisplayLogoByTypeOfObject(toDisplay, _heightLine); if (!disable && !_dragSettings.IsDragging) { Rect logoContent = GUILayoutUtility.GetLastRect(); if (logoContent.Contains(Event.current.mousePosition)) { EditorGUIUtility.AddCursorRect(logoContent, MouseCursor.MoveArrow); if (Event.current.type == EventType.MouseDown) { _listToDisplayCopy = ListToDisplay.ToObjectList(); _dragSettings.StartDragging(index, logoContent); Event.current.Use(); } } } //display main button EditorGUI.BeginDisabledGroup(toDisplay == null); { string nameObjectToSelect; if (toDisplay == null) { nameObjectToSelect = !string.IsNullOrEmpty(nameInListPath) ? ObjectNames.NicifyVariableName(nameInListPath) : " --- not found --- "; } else { nameObjectToSelect = ObjectNames.NicifyVariableName(toDisplay.name); } GUIContent buttonSelectContent = ShortenNameIfNeeded(nameObjectToSelect, width, widthButtonWithoutExtent); buttonSelectContent.tooltip = "Clic to select, Right clic to Pin only"; if (GUILayout.Button(buttonSelectContent, BookMarkButtonOptions.GuiStyle, GUILayout.ExpandWidth(true), GUILayout.Height(_heightLine))) { if (Event.current.button == 0) { OnSelectItem?.Invoke(index); } else { OnPinItem?.Invoke(index); } return; } } EditorGUI.EndDisabledGroup(); //display special scene buttons if (toDisplay == null && OnInfoItem != null) { bool selectScene = false; bool goToScene = false; DisplaySpecialSceneSettings(ref selectScene, ref goToScene); if (goToScene) { OnInfoForceItem?.Invoke(index); return; } else if (selectScene) { OnInfoItem?.Invoke(index); return; } } //display delete button GUIContent buttonDeletContent = EditorGUIUtility.IconContent(DELETE_ICON); buttonDeletContent.tooltip = "Remove from list"; if (GUILayout.Button(buttonDeletContent, BookMarkButtonOptions.GuiStyle, GUILayout.ExpandWidth(false), GUILayout.MaxWidth(WIDTH_BUTTON_HOVER), GUILayout.Height(_heightLine)) && Event.current.button == 0) { OnRemoveItem?.Invoke(index); return; } if (_calculateExtent) { GUILayout.Label("", GUILayout.Width(widthExtent), GUILayout.Height(_heightLine)); } } } EditorGUI.EndDisabledGroup(); }
private string UpdateModeToString(VFXUpdateMode mode) { return(ObjectNames.NicifyVariableName(mode.ToString())); }
static void OnSceneGUI(SceneView sceneView) { Event e = Event.current; if (e.type != EventType.Used && e.control && e.isMouse && e.button == 1) { switch (e.rawType) { case EventType.MouseDown: mouseRightIsDownWithoutDrag = true; break; case EventType.MouseDrag: mouseRightIsDownWithoutDrag = false; break; } //The actual CTRL+RIGHT-MOUSE functionality if (mouseRightIsDownWithoutDrag && e.rawType == EventType.MouseUp) { SelectionPopup.totalSelection = GetAllOverlapping(e.mousePosition).ToArray(); SelectionPopup.icons = new GUIContent[SelectionPopup.totalSelection.Length][]; SelectionPopup.iconsOffsets = new float[SelectionPopup.totalSelection.Length]; SelectionPopup.iconsOffsetTargets = new float[SelectionPopup.totalSelection.Length]; for (var t = 0; t < SelectionPopup.totalSelection.Length; t++) { GameObject gO = SelectionPopup.totalSelection[t]; Component[] cS = gO.GetComponents <Component>(); GUIContent[] icons = new GUIContent[cS.Length - 1]; for (var i = 1; i < cS.Length; i++) { if (cS[i] == null) { icons[i - 1] = GUIContent.none; continue; } //Skip the Transform component because it's always the first object icons[i - 1] = new GUIContent(AssetPreview.GetMiniThumbnail(cS[i]), ObjectNames.NicifyVariableName(cS[i].GetType().Name)); } SelectionPopup.icons[t] = icons; SelectionPopup.iconsOffsets[t] = 0; SelectionPopup.iconsOffsetTargets[t] = 0; } Vector2 selectionPosition = e.mousePosition; float xOffset; //Screen-rect limits offset if (selectionPosition.x + width > sceneView.position.width) { xOffset = -width; } else { xOffset = 0; } int value = Mathf.CeilToInt(((selectionPosition.y + height * SelectionPopup.totalSelection.Length) - sceneView.position.height + 10) / height); SelectionPopup.scrollPosition = Mathf.Max(0, value); SelectionPopup popup = SelectionPopup.ShowModal( new Rect( sceneView.position.x + e.mousePosition.x + xOffset, sceneView.position.y + e.mousePosition.y + height * 1.5f, width, height * SelectionPopup.totalSelection.Length + 1 + 5 * 2 ) ); if (popup == null) { e.Use(); return; } e.alt = false; mouseRightIsDownWithoutDrag = false; SelectionPopup.RefreshSelection(); e.Use(); } } }
void InitializeView() { if (data.block == null) { return; } if (data.block is Events.HLAction || data.block is Events.HLCondition) { InitializeHLBlock(data.block); return; } var fields = EditorReflectionUtility.GetFields(data.block.GetType()); if (fields != null && fields.Length > 0) { for (int idx = 0; idx < fields.Length; idx++) { FieldInfo field = fields[idx]; if (uNodeGUIUtility.IsHide(field, data.block)) { continue; } Type type = field.FieldType; if (type == typeof(MemberData)) { MemberData member = field.GetValueOptimized(data.block) as MemberData; object[] fieldAttribute = field.GetCustomAttributes(true); if (!ReflectionUtils.TryCorrectingAttribute(data.block, ref fieldAttribute)) { continue; } var filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttribute); if (member == null) { if (filter != null && !filter.SetMember && !filter.OnlyGetType && ReflectionUtils.CanCreateInstance(filter.GetActualType())) { member = new MemberData(ReflectionUtils.CreateInstance(filter.GetActualType())); } else if (filter != null && !filter.SetMember && !filter.OnlyGetType) { member = MemberData.none; } field.SetValueOptimized(data.block, member); Repaint(); } bool hasDependencies = EditorReflectionUtility.HasFieldDependencies(new string[] { field.Name }, fields); var port = AddPort(new PortData() { getPortName = () => ObjectNames.NicifyVariableName(field.Name), getPortType = () => filter?.GetActualType() ?? typeof(object), getPortValue = () => field.GetValueOptimized(data.block), filter = filter, onValueChanged = (obj) => { RegisterUndo(); member = obj as MemberData; field.SetValueOptimized(data.block, member); Repaint(); if (hasDependencies) { owner.nodeView.MarkRepaint(); } }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } else if (type == typeof(MultipurposeMember)) { InitMultipurposeMember(field); } else { object fieldVal = field.GetValueOptimized(data.block); object[] fieldAttribute = field.GetCustomAttributes(true); if (!ReflectionUtils.TryCorrectingAttribute(data.block, ref fieldAttribute)) { continue; } bool hasDependencies = EditorReflectionUtility.HasFieldDependencies(new string[] { field.Name }, fields); var filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttribute); ControlConfig config = new ControlConfig() { owner = owner.nodeView, value = fieldVal, type = type, filter = filter, onValueChanged = (obj) => { RegisterUndo(); field.SetValueOptimized(data.block, obj); Repaint(); if (hasDependencies) { owner.nodeView.MarkRepaint(); } }, }; var valueControl = UIElementUtility.CreateControl(type, config, true); AddControl(field.Name, new ControlView(valueControl, true)); if (fieldVal is IList <MemberData> ) { IList <MemberData> members = fieldVal as IList <MemberData>; if (members != null) { for (int i = 0; i < members.Count; i++) { int index = i; var member = members[i]; if (member == null) { if (filter != null && !filter.SetMember && !filter.OnlyGetType && ReflectionUtils.CanCreateInstance(filter.GetActualType())) { member = new MemberData(ReflectionUtils.CreateInstance(filter.GetActualType())); } else { member = MemberData.none; } members[index] = member; field.SetValueOptimized(data.block, members); Repaint(); } var port = AddPort(new PortData() { getPortName = () => "Element " + index.ToString(), getPortType = () => filter?.GetActualType() ?? typeof(object), getPortValue = () => (field.GetValueOptimized(data.block) as IList <MemberData>)[index], filter = filter, onValueChanged = (obj) => { RegisterUndo(); member = obj as MemberData; members[index] = member; field.SetValueOptimized(data.block, members); Repaint(); }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } } } else if (fieldVal is IList) { IList list = fieldVal as IList; if (list != null) { for (int i = 0; i < list.Count; i++) { int index = i; var element = list[i]; ControlConfig cfg = new ControlConfig() { owner = owner.nodeView, value = fieldVal, type = type, filter = filter, onValueChanged = (obj) => { RegisterUndo(); field.SetValueOptimized(data.block, obj); Repaint(); }, }; var elementControl = UIElementUtility.CreateControl(type, cfg, true); AddControl("Element " + index, new ControlView(elementControl, true)); } } } } } } }
string GetUniqueRecorderName(string desiredName) { return(ObjectNames.GetUniqueName(m_ControllerSettings.RecorderSettings.Select(r => r.name).ToArray(), desiredName)); }
void InitMultipurposeMember(FieldInfo field) { MultipurposeMember member = field.GetValueOptimized(data.block) as MultipurposeMember; object[] fieldAttribute = field.GetCustomAttributes(true); if (!ReflectionUtils.TryCorrectingAttribute(data.block, ref fieldAttribute)) { return; } if (member == null) { member = new MultipurposeMember(); field.SetValueOptimized(data.block, member); Repaint(); } if (member.target == null || member.target.isTargeted && member.target.IsTargetingPinOrNode) { var filter = ReflectionUtils.GetAttribute <FilterAttribute>(fieldAttribute) ?? new FilterAttribute() { MaxMethodParam = int.MaxValue, }; var port = AddPort(new PortData() { getPortName = () => field.Name, getPortType = () => typeof(MemberData), getPortValue = () => member.target, filter = filter, onValueChanged = (obj) => { var val = obj as MemberData; RegisterUndo(); if (member.target.targetType != val.targetType || val.targetType != MemberData.TargetType.Values) { member.target = val; owner.nodeView.MarkRepaint(); MemberDataUtility.UpdateMultipurposeMember(member); } else { member.target = val; } field.SetValueOptimized(data.block, member); Repaint(); }, }); var control = port.portData.InstantiateControl(true); control.HideInstance(true); port.Add(new ControlView(control, true)); //ControlConfig config = new ControlConfig() { // owner = owner, // value = member.target, // type = typeof(MemberData), // filter = filter, // onValueChanged = (obj) => { // var val = obj as MemberData; // RegisterUndo(); // if(member.target.targetType != val.targetType || val.targetType != MemberData.TargetType.Values) { // member.target = val; // owner.MarkRepaint(); // uNodeEditorUtility.UpdateMultipurposeMember(member); // } else { // member.target = val; // } // field.SetValue(data.actionEvent, member); // Repaint(); // }, //}; //MemberControl control = new MemberControl(config, true); //AddControl(field.Name, new ControlView(control, true)); } if (member.target.isTargeted) { if (member.target.targetType != MemberData.TargetType.Values) { if (!member.target.isStatic && (!member.target.IsTargetingUNode || !uNodePreference.GetPreference().hideUNodeInstance) && member.target.targetType != MemberData.TargetType.Type && member.target.targetType != MemberData.TargetType.Null) { MemberDataUtility.UpdateMemberInstance(member.target, member.target.startType); var port = AddPort(new PortData() { portID = "Instance", getPortName = () => "Instance", getPortType = () => member.target.startType, getPortValue = () => member.target?.instance, filter = new FilterAttribute(member.target.startType), onValueChanged = (o) => { RegisterUndo(); member.target.instance = o; field.SetValueOptimized(data.block, member); }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } else if (!uNodePreference.GetPreference().hideUNodeInstance&& member.target.IsTargetingUNode && !member.target.IsTargetingNode) { MemberDataUtility.UpdateMemberInstance(member.target, member.target.startType); var port = AddPort(new PortData() { portID = "Instance", getPortName = () => "", getPortType = () => typeof(uNodeRoot), getPortValue = () => member.target?.instance, filter = new FilterAttribute(typeof(uNodeRoot)), onValueChanged = (o) => { RegisterUndo(); member.target.instance = o; field.SetValueOptimized(data.block, member); }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } } if (member.target.SerializedItems?.Length > 0) { MemberInfo[] members = null; if (uNodePreference.GetPreference().inEditorDocumentation) { members = member.target.GetMembers(false); if (members != null && members.Length > 0 && members.Length + 1 != member.target.SerializedItems.Length) { members = null; } } uNodeFunction objRef = null; switch (member.target.targetType) { case MemberData.TargetType.uNodeFunction: { uNodeRoot root = member.target.GetInstance() as uNodeRoot; if (root != null) { var gTypes = member.target.GenericTypes[0]; objRef = root.GetFunction(member.target.startName, gTypes != null ? gTypes.Length : 0, member.target.ParameterTypes[0]); } break; } } int totalParam = 0; bool flag = false; for (int i = 0; i < member.target.SerializedItems.Length; i++) { if (i != 0) { if (members != null && (member.target.isDeepTarget || !member.target.IsTargetingUNode)) { MemberInfo mData = members[i - 1]; if (mData is MethodInfo || mData is ConstructorInfo) { var method = mData as MethodInfo; var parameters = method != null?method.GetParameters() : (mData as ConstructorInfo).GetParameters(); if (parameters.Length > 0) { totalParam++; if (totalParam > 1) { flag = true; break; } } } } } } totalParam = 0; int methodDrawCount = 1; for (int i = 0; i < member.target.SerializedItems.Length; i++) { if (i != 0) { if (members != null && (member.target.isDeepTarget || !member.target.IsTargetingUNode)) { MemberInfo memberInfo = members[i - 1]; if (memberInfo is MethodInfo || memberInfo is ConstructorInfo) { var method = memberInfo as MethodInfo; var documentation = XmlDoc.XMLFromMember(memberInfo); if (flag) { AddControl(memberInfo.Name, null); } var parameters = method != null?method.GetParameters() : (memberInfo as ConstructorInfo).GetParameters(); if (parameters.Length > 0) { while (parameters.Length + totalParam > member.parameters.Length) { ArrayUtility.Add(ref member.parameters, MemberData.empty); } for (int x = 0; x < parameters.Length; x++) { var parameter = parameters[x]; if (parameter.ParameterType != null) { int index = totalParam; var param = member.parameters[index]; var port = AddPort(new PortData() { getPortName = () => ObjectNames.NicifyVariableName(parameter.Name), getPortType = () => parameter.ParameterType, getPortValue = () => param, filter = new FilterAttribute(parameter.ParameterType), onValueChanged = (obj) => { RegisterUndo(); param = obj as MemberData; member.parameters[index] = param; field.SetValueOptimized(data.block, member); Repaint(); }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } totalParam++; } continue; } } } } System.Type[] paramsType = member.target.ParameterTypes[i]; if (paramsType != null && paramsType.Length > 0) { if (flag) { AddControl("Method " + (methodDrawCount), null); methodDrawCount++; } while (paramsType.Length + totalParam > member.parameters.Length) { ArrayUtility.Add(ref member.parameters, MemberData.none); } for (int x = 0; x < paramsType.Length; x++) { System.Type PType = paramsType[x]; if (member.parameters[totalParam] == null) { member.parameters[totalParam] = MemberData.none; } if (PType != null) { int index = totalParam; var param = member.parameters[index]; string pLabel; if (objRef != null) { pLabel = objRef.parameters[x].name; } else { pLabel = "P" + (x + 1); } var port = AddPort(new PortData() { getPortName = () => ObjectNames.NicifyVariableName(pLabel), getPortType = () => PType, getPortValue = () => param, filter = new FilterAttribute(PType), onValueChanged = (obj) => { RegisterUndo(); param = obj as MemberData; member.parameters[index] = param; field.SetValueOptimized(data.block, member); Repaint(); }, }); port.Add(new ControlView(port.portData.InstantiateControl(true), true)); } totalParam++; } } } while (member.parameters.Length > totalParam) { ArrayUtility.RemoveAt(ref member.parameters, member.parameters.Length - 1); } } } }
public override void DrawParameter(ref object param, ParameterInfo propertyInfo) { param = EditorGUILayout.IntField(ObjectNames.NicifyVariableName(propertyInfo.Name), (int)param); }
public static void Open() { GetWindow <ExampleGraphEditorWindow>(ObjectNames.NicifyVariableName(nameof(ExampleGraphEditorWindow))); }
public static string CodeToString(KeyCode code) { switch (code) { case KeyCode.Exclaim: return("!"); case KeyCode.DoubleQuote: return("\""); case KeyCode.Hash: return("#"); case KeyCode.Dollar: return("$"); case KeyCode.Ampersand: return("&"); case KeyCode.Quote: return("\'"); case KeyCode.LeftParen: return("("); case KeyCode.RightParen: return(")"); case KeyCode.Asterisk: return("*"); case KeyCode.Plus: return("+"); case KeyCode.Comma: return(","); case KeyCode.Minus: return("-"); case KeyCode.Period: return("."); case KeyCode.Slash: return("/"); case KeyCode.Alpha0: return("0"); case KeyCode.Alpha1: return("1"); case KeyCode.Alpha2: return("2"); case KeyCode.Alpha3: return("3"); case KeyCode.Alpha4: return("4"); case KeyCode.Alpha5: return("5"); case KeyCode.Alpha6: return("6"); case KeyCode.Alpha7: return("7"); case KeyCode.Alpha8: return("8"); case KeyCode.Alpha9: return("9"); case KeyCode.Colon: return(":"); case KeyCode.Semicolon: return(";"); case KeyCode.Less: return("<"); case KeyCode.Equals: return("="); case KeyCode.Greater: return(">"); case KeyCode.Question: return("?"); case KeyCode.At: return("@"); case KeyCode.LeftBracket: return("["); case KeyCode.Backslash: return("\\"); case KeyCode.RightBracket: return("]"); case KeyCode.Caret: return("^"); case KeyCode.Underscore: return("_"); case KeyCode.BackQuote: return("`"); case KeyCode.KeypadPeriod: return("Keypad '.'"); case KeyCode.KeypadDivide: return("Keypad '/'"); case KeyCode.KeypadMultiply: return("Keypad '*'"); case KeyCode.KeypadMinus: return("Keypad '-'"); case KeyCode.KeypadPlus: return("Keypad '+'"); case KeyCode.KeypadEquals: return("Keypad '='"); default: return(ObjectNames.NicifyVariableName(code.ToString())); } }
private void RenderManualConstraintMenu() { for (int i = 0; i < selectedConstraints.arraySize; i++) { SerializedProperty constraintProperty = selectedConstraints.GetArrayElementAtIndex(i); var buttonAction = RenderManualConstraintItem(constraintProperty, true); if (buttonAction == EntryAction.Detach) { indicesToRemove.Add(i); } else if (buttonAction == EntryAction.Highlight) { string constraintName = constraintProperty.objectReferenceValue.GetType().Name; Highlighter.Highlight("Inspector", $"{ObjectNames.NicifyVariableName(constraintName)} (Script)"); EditorGUIUtility.ExitGUI(); } } // add buttons { using (new EditorGUILayout.HorizontalScope()) { if (EditorGUILayout.DropdownButton(new GUIContent("Add Entry", "Attach an already existing component from this gameobject to the constraint manager selection."), FocusType.Keyboard)) { // create the menu and add items to it GenericMenu menu = new GenericMenu(); var constraints = constraintManager.gameObject.GetComponents <TransformConstraint>(); bool hasEntries = false; foreach (var constraint in constraints) { // only show available constraints that haven't been added yet var existingConstraint = constraintManager.SelectedConstraints.Find(t => t == constraint); if (existingConstraint == null) { hasEntries = true; string constraintName = constraint.GetType().Name; menu.AddItem(new GUIContent(constraintName), false, t => AttachConstraint((TransformConstraint)t), constraint); } } // if all constraint components are already part of the list display disabled "no constraint available" entry if (hasEntries == false) { var guiEnabledRestore = GUI.enabled; GUI.enabled = false; menu.AddItem(new GUIContent("No constraint available", "Either there's no constraint attached to this game object or all available constraints " + "are already part of the list."), false, null); GUI.enabled = guiEnabledRestore; } menu.ShowAsContext(); } if (EditorGUILayout.DropdownButton(new GUIContent("Add New Constraint", "Add a constraint to the gameobject and attach to this constraint manager selection."), FocusType.Keyboard)) { // create the menu and add items to it GenericMenu menu = new GenericMenu(); var type = typeof(TransformConstraint); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetLoadableTypes()) .Where(p => type.IsAssignableFrom(p) && !p.IsAbstract); foreach (var derivedType in types) { menu.AddItem(new GUIContent(derivedType.Name), false, t => AddNewConstraint((Type)t), derivedType); } menu.ShowAsContext(); } } } }
/// <summary> Draw an editable list of instance ports. Port names are named as "[fieldName] [index]" </summary> /// <param name="fieldName">Supply a list for editable values</param> /// <param name="type">Value type of added instance ports</param> /// <param name="serializedObject">The serializedObject of the node</param> /// <param name="connectionType">Connection type of added instance ports</param> public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { XNode.Node node = serializedObject.targetObject as XNode.Node; SerializedProperty arrayData = serializedObject.FindProperty(fieldName); bool hasArrayData = arrayData != null && arrayData.isArray; int arraySize = hasArrayData ? arrayData.arraySize : 0; Predicate <string> isMatchingInstancePort = x => { string[] split = x.Split(' '); if (split != null && split.Length == 2) { return(split[0] == fieldName); } else { return(false); } }; List <XNode.NodePort> instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList(); for (int i = 0; i < instancePorts.Count(); i++) { GUILayout.BeginHorizontal(); // 'Remove' button if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { // Clear the removed ports connections instancePorts[i].ClearConnections(); // Move following connections one step up to replace the missing connection for (int k = i + 1; k < instancePorts.Count(); k++) { for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { XNode.NodePort other = instancePorts[k].GetConnection(j); instancePorts[k].Disconnect(other); instancePorts[k - 1].Connect(other); } } // Remove the last instance port, to avoid messing up the indexing node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) { arrayData.DeleteArrayElementAtIndex(i); arraySize--; // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues if (instancePorts.Count <= arraySize) { while (instancePorts.Count <= arraySize) { arrayData.DeleteArrayElementAtIndex(--arraySize); } Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } i--; GUILayout.EndHorizontal(); } else { if (hasArrayData) { if (i < arraySize) { SerializedProperty itemData = arrayData.GetArrayElementAtIndex(i); if (itemData != null) { EditorGUILayout.PropertyField(itemData, new GUIContent(ObjectNames.NicifyVariableName(fieldName) + " " + i), true); } else { EditorGUILayout.LabelField("[Missing array data]"); } } else { EditorGUILayout.LabelField("[Out of bounds]"); } } else { EditorGUILayout.LabelField(ObjectNames.NicifyVariableName(instancePorts[i].fieldName)); } GUILayout.EndHorizontal(); NodeEditorGUILayout.AddPortField(node.GetPort(instancePorts[i].fieldName)); } // GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); // 'Add' button if (GUILayout.Button("+", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { string newName = fieldName + " 0"; int i = 0; while (node.HasPort(newName)) { newName = fieldName + " " + (++i); } if (io == XNode.NodePort.IO.Output) { node.AddInstanceOutput(type, connectionType, newName); } else { node.AddInstanceInput(type, connectionType, newName); } serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) { arrayData.InsertArrayElementAtIndex(arraySize); } serializedObject.ApplyModifiedProperties(); } GUILayout.EndHorizontal(); }
public override void OnInspectorGUI() { serializedObject.Update(); DrawPropertiesExcluding(serializedObject, "m_Script", "Data"); GUILayout.Space(2); dataArray = serializedObject.FindProperty(nameof(ComposableObject.Data)); CleanDataArray(); for (int i = 0; i < dataArray.arraySize; i++) { var step = dataArray.GetArrayElementAtIndex(i); var stepSo = new SerializedObject(step.objectReferenceValue); var stepType = step.objectReferenceValue.GetType(); var isSingleLine = stepType.GetCustomAttributes <SingleLineAttribute>().Any(); UnityEditor.Editor editor; if (Editors.ContainsKey(step.objectReferenceValue)) { editor = Editors[step.objectReferenceValue]; } else { Editors[step.objectReferenceValue] = editor = CreateEditor(step.objectReferenceValue); } try { var title = ObjectNames.NicifyVariableName(stepType.Name); var foldoutRect = GUILayoutUtility.GetRect(currentViewWidth, singleLineHeight + 3); GUI.Box(new Rect(foldoutRect.x - 14, foldoutRect.y - 1, foldoutRect.width + 20, foldoutRect.height + 1), string.Empty); var standardSize = singleLineHeight + standardVerticalSpacing; Rect deleteRect = new Rect(foldoutRect.x + 1 + foldoutRect.width - standardSize, foldoutRect.y + 1, standardSize, standardSize); var popupIcon = IconContent("_Popup"); if (Event.current.type == EventType.Repaint) { GUIStyle.none.Draw(deleteRect, popupIcon, false, false, false, false); } if (Event.current.type == EventType.MouseUp && deleteRect.Contains(Event.current.mousePosition)) { ShowContextMenu(i, step); } if (isSingleLine) { var so = new SerializedObject(step.objectReferenceValue); var iter = so.GetIterator().Copy(); iter.NextVisible(true); if ("m_script".Equals(iter.name, System.StringComparison.OrdinalIgnoreCase)) { iter.NextVisible(false); } EditorHelpers.AddField(new Rect(foldoutRect.x, foldoutRect.y + 1, foldoutRect.width - 20, foldoutRect.height - 1), iter, ObjectNames.NicifyVariableName(stepType.Name)); } else { step.isExpanded = EditorGUI.Foldout(foldoutRect, step.isExpanded, title); if (step.isExpanded) { editor.serializedObject.Update(); editor.OnInspectorGUI(); if (GUI.changed) { EditorUtility.SetDirty(editor.serializedObject.targetObject); editor.serializedObject.ApplyModifiedProperties(); Repaint(); } Repaint(); editor.serializedObject.ApplyModifiedProperties(); } } } catch (Exception e) { Debug.LogException(e); } } var composableObject = target as ComposableObject; var size = AddScriptWindow.Styles.addButtonStyle.CalcSize(new GUIContent($"Add {ObjectNames.NicifyVariableName(composableObject.ElementType.Name)}")); var rect = GUILayoutUtility.GetRect(size.x, size.y); rect.width = size.x; rect.y += standardVerticalSpacing; rect.x = (currentViewWidth / 2) - (rect.width / 2); OnAddElementGUI(rect, composableObject); if (GUI.changed) { EditorUtility.SetDirty(serializedObject.targetObject); serializedObject.ApplyModifiedProperties(); Repaint(); } Repaint(); serializedObject.ApplyModifiedProperties(); }
public static void ShowGUI(SceneView sceneView, bool haveOffset = true) { if (!localStyles) { miniTextStyle = new GUIStyle(EditorStyles.miniLabel); miniTextStyle.contentOffset = new Vector2(0, -1); textInputStyle = new GUIStyle(EditorStyles.miniTextField); textInputStyle.padding.top--; textInputStyle.margin.top += 2; localStyles = true; helperSurfaceFlagStrings = Enum.GetNames(typeof(HelperSurfaceFlags)).Select(x => ObjectNames.NicifyVariableName(x)).ToArray(); } GUIStyleUtility.InitStyles(); if (sceneView != null) { float height = sceneView.position.height; //Screen.height; float width = sceneView.position.width; //Screen.width; Rect bottomBarRect; if (haveOffset) { #if UNITY_5_5_OR_NEWER bottomBarRect = new Rect(0, height - (GUIStyleUtility.BottomToolBarHeight + 18), width, GUIStyleUtility.BottomToolBarHeight); #else bottomBarRect = new Rect(0, height - (GUIStyleUtility.BottomToolBarHeight + SceneView.kToolbarHeight + 1), width, GUIStyleUtility.BottomToolBarHeight); #endif } else { bottomBarRect = new Rect(0, height - (GUIStyleUtility.BottomToolBarHeight + 1), width, GUIStyleUtility.BottomToolBarHeight); } try { Handles.BeginGUI(); GUILayout.BeginArea(bottomBarRect, GUIStyleUtility.BottomToolBarStyle); OnBottomBarGUI(sceneView); GUILayout.EndArea(); int controlID = GUIUtility.GetControlID(BottomBarGUIHash, FocusType.Keyboard, bottomBarRect); var type = Event.current.GetTypeForControl(controlID); //Debug.Log(controlID + " " + GUIUtility.hotControl + " " + type + " " + bottomBarRect.Contains(Event.current.mousePosition)); switch (type) { case EventType.MouseDown: { if (bottomBarRect.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = controlID; GUIUtility.keyboardControl = controlID; Event.current.Use(); } break; } case EventType.MouseMove: { if (bottomBarRect.Contains(Event.current.mousePosition)) { Event.current.Use(); } break; } case EventType.MouseUp: { if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; Event.current.Use(); } break; } case EventType.MouseDrag: { if (GUIUtility.hotControl == controlID) { Event.current.Use(); } break; } case EventType.ScrollWheel: { if (bottomBarRect.Contains(Event.current.mousePosition)) { Event.current.Use(); } break; } } //TooltipUtility.HandleAreaOffset(new Vector2(-bottomBarRect.xMin, -bottomBarRect.yMin)); } finally { Handles.EndGUI(); } } }
public override string ToString() { m_Text = m_ScriptPrescription.m_Template; m_Writer = new StringWriter(); m_Writer.NewLine = "\n"; // Make sure all line endings are Unix (Mac OS X) format m_Text = Regex.Replace(m_Text, @"\r\n?", delegate(Match m) { return("\n"); }); // Class Name m_Text = m_Text.Replace("$ClassName", ClassName); m_Text = m_Text.Replace("$NicifiedClassName", ObjectNames.NicifyVariableName(ClassName)); m_Text = m_Text.Replace("$NicifiedClassName", ObjectNames.NicifyVariableName(ClassName)); m_Text = m_Text.Replace("$ACTIONID", Regex.Replace(ClassName, "[a-zA-Z]", "", RegexOptions.IgnoreCase)); // Other replacements foreach (KeyValuePair <string, string> kvp in m_ScriptPrescription.m_StringReplacements) { m_Text = m_Text.Replace(kvp.Key, kvp.Value); } // Functions // Find $Functions keyword including leading tabs Match match = Regex.Match(m_Text, @"(\t*)\$Functions"); if (match.Success) { // Set indent level to number of tabs before $Functions keyword IndentLevel = match.Groups[1].Value.Length; bool hasFunctions = false; if (m_ScriptPrescription.m_Functions != null) { foreach (var function in m_ScriptPrescription.m_Functions.Where(f => f.include)) { WriteFunction(function); WriteBlankLine(); hasFunctions = true; } // Replace $Functions keyword plus newline with generated functions text if (hasFunctions) { m_Text = m_Text.Replace(match.Value + "\n", m_Writer.ToString()); } } if (!hasFunctions) { if (m_ScriptPrescription.m_Lang == Language.Boo && !m_Text.Contains("def")) { // Replace $Functions keyword with "pass" if no functions in Boo m_Text = m_Text.Replace(match.Value, m_Indentation + "pass"); } else { // Otherwise just remove $Functions keyword plus newline m_Text = m_Text.Replace(match.Value + "\n", string.Empty); } } } // Put curly vraces on new line if specified in editor prefs if (EditorPrefs.GetBool("CurlyBracesOnNewLine")) { PutCurveBracesOnNewLine(); } // Return the text of the script return(m_Text); }
private static ReorderableList CreateReorderableList(string fieldName, List <XNode.NodePort> instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action <ReorderableList> onCreation) { bool hasArrayData = arrayData != null && arrayData.isArray; int arraySize = hasArrayData ? arrayData.arraySize : 0; XNode.Node node = serializedObject.targetObject as XNode.Node; ReorderableList list = new ReorderableList(instancePorts, null, true, true, true, true); string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { XNode.NodePort port = node.GetPort(fieldName + " " + index); if (hasArrayData) { if (arrayData.arraySize <= index) { EditorGUI.LabelField(rect, "Invalid element " + index); return; } SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemData, true); } else { EditorGUI.LabelField(rect, port.fieldName); } Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); NodeEditorGUILayout.PortField(pos, port); }; list.elementHeightCallback = (int index) => { if (hasArrayData) { if (arrayData.arraySize <= index) { return(EditorGUIUtility.singleLineHeight); } SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); return(EditorGUI.GetPropertyHeight(itemData)); } else { return(EditorGUIUtility.singleLineHeight); } }; list.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, label); }; list.onSelectCallback = (ReorderableList rl) => { reorderableListIndex = rl.index; }; list.onReorderCallback = (ReorderableList rl) => { // Move up if (rl.index > reorderableListIndex) { for (int i = reorderableListIndex; i < rl.index; ++i) { XNode.NodePort port = node.GetPort(fieldName + " " + i); XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; } } // Move down else { for (int i = reorderableListIndex; i > rl.index; --i) { XNode.NodePort port = node.GetPort(fieldName + " " + i); XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; } } // Apply changes serializedObject.ApplyModifiedProperties(); serializedObject.Update(); // Move array data if there is any if (hasArrayData) { arrayData.MoveArrayElement(reorderableListIndex, rl.index); } // Apply changes serializedObject.ApplyModifiedProperties(); serializedObject.Update(); NodeEditorWindow.current.Repaint(); EditorApplication.delayCall += NodeEditorWindow.current.Repaint; }; list.onAddCallback = (ReorderableList rl) => { // Add instance port postfixed with an index number string newName = fieldName + " 0"; int i = 0; while (node.HasPort(newName)) { newName = fieldName + " " + (++i); } if (io == XNode.NodePort.IO.Output) { node.AddInstanceOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName); } else { node.AddInstanceInput(type, connectionType, typeConstraint, newName); } serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) { arrayData.InsertArrayElementAtIndex(arraySize); } serializedObject.ApplyModifiedProperties(); }; list.onRemoveCallback = (ReorderableList rl) => { int index = rl.index; // Clear the removed ports connections instancePorts[index].ClearConnections(); // Move following connections one step up to replace the missing connection for (int k = index + 1; k < instancePorts.Count(); k++) { for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { XNode.NodePort other = instancePorts[k].GetConnection(j); instancePorts[k].Disconnect(other); instancePorts[k - 1].Connect(other); } } // Remove the last instance port, to avoid messing up the indexing node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) { arrayData.DeleteArrayElementAtIndex(index); arraySize--; // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues if (instancePorts.Count <= arraySize) { while (instancePorts.Count <= arraySize) { arrayData.DeleteArrayElementAtIndex(--arraySize); } UnityEngine.Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } }; if (hasArrayData) { int instancePortCount = instancePorts.Count; while (instancePortCount < arraySize) { // Add instance port postfixed with an index number string newName = arrayData.name + " 0"; int i = 0; while (node.HasPort(newName)) { newName = arrayData.name + " " + (++i); } if (io == XNode.NodePort.IO.Output) { node.AddInstanceOutput(type, connectionType, typeConstraint, newName); } else { node.AddInstanceInput(type, connectionType, typeConstraint, newName); } EditorUtility.SetDirty(node); instancePortCount++; } while (arraySize < instancePortCount) { arrayData.InsertArrayElementAtIndex(arraySize); arraySize++; } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } if (onCreation != null) { onCreation(list); } return(list); }
public static void Button(UnityEngine.Object target, MethodInfo methodInfo) { bool visible = ButtonUtility.IsVisible(target, methodInfo); if (!visible) { return; } if (methodInfo.GetParameters().All(p => p.IsOptional)) { ButtonAttribute buttonAttribute = (ButtonAttribute)methodInfo.GetCustomAttributes(typeof(ButtonAttribute), true)[0]; string buttonText = string.IsNullOrEmpty(buttonAttribute.Text) ? ObjectNames.NicifyVariableName(methodInfo.Name) : buttonAttribute.Text; bool buttonEnabled = ButtonUtility.IsEnabled(target, methodInfo); EButtonEnableMode mode = buttonAttribute.SelectedEnableMode; buttonEnabled &= mode == EButtonEnableMode.Always || mode == EButtonEnableMode.Editor && !Application.isPlaying || mode == EButtonEnableMode.Playmode && Application.isPlaying; bool methodIsCoroutine = methodInfo.ReturnType == typeof(IEnumerator); if (methodIsCoroutine) { buttonEnabled &= (Application.isPlaying ? true : false); } EditorGUI.BeginDisabledGroup(!buttonEnabled); if (GUILayout.Button(buttonText, _buttonStyle)) { object[] defaultParams = methodInfo.GetParameters().Select(p => p.DefaultValue).ToArray(); IEnumerator methodResult = methodInfo.Invoke(target, defaultParams) as IEnumerator; if (!Application.isPlaying) { // Set target object and scene dirty to serialize changes to disk EditorUtility.SetDirty(target); PrefabStage stage = PrefabStageUtility.GetCurrentPrefabStage(); if (stage != null) { // Prefab mode EditorSceneManager.MarkSceneDirty(stage.scene); } else { // Normal scene EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } } else if (methodResult != null && target is MonoBehaviour behaviour) { behaviour.StartCoroutine(methodResult); } } EditorGUI.EndDisabledGroup(); } else { string warning = typeof(ButtonAttribute).Name + " works only on methods with no parameters"; HelpBox_Layout(warning, MessageType.Warning, context: target, logToConsole: true); } }
public static DS_ProductLocation.SP_GetProductLocationQuantityDataTable GetProductLocationQuantity(int?productLocationID, ObjectNames tableName, bool isOnline, byte[] b) { return(Instance.GetProductLocationQuantity(productLocationID, (int)tableName, isOnline, b)); }
protected string NicifyName(string name) => ObjectNames.NicifyVariableName(name);
public ChannelMixerControlView(string label, float minimum, float maximum, AbstractMaterialNode node, PropertyInfo propertyInfo) { m_Node = node; m_PropertyInfo = propertyInfo; m_ChannelMixer = (ChannelMixerNode.ChannelMixer)m_PropertyInfo.GetValue(m_Node, null); m_OutChannel = 0; m_Minimum = minimum; m_Maximum = maximum; if (propertyInfo.PropertyType != typeof(ChannelMixerNode.ChannelMixer)) { throw new ArgumentException("Property must be of type ChannelMixer.", "propertyInfo"); } label = label ?? ObjectNames.NicifyVariableName(propertyInfo.Name); if (!string.IsNullOrEmpty(label)) { Add(new Label(label)); } var buttonPanel = new VisualElement { name = "buttonPanel" }; Action changedOutputRed = () => OnClickButton(0); var outputButtonRed = new Button(changedOutputRed); outputButtonRed.Add(new Label("R")); buttonPanel.Add(outputButtonRed); Action changedOutputGreen = () => OnClickButton(1); var outputButtonGreen = new Button(changedOutputGreen); outputButtonGreen.Add(new Label("G")); buttonPanel.Add(outputButtonGreen); Action changedOutputBlue = () => OnClickButton(2); var outputButtonBlue = new Button(changedOutputBlue); outputButtonBlue.Add(new Label("B")); buttonPanel.Add(outputButtonBlue); Add(buttonPanel); var redSliderPanel = new VisualElement { name = "sliderPanel" }; redSliderPanel.Add(new Label("R")); Action <float> changedRedIn = (s) => { OnChangeSlider(s, 0); }; m_RedSlider = new Slider(m_Minimum, m_Maximum, changedRedIn); redSliderPanel.Add(m_RedSlider); m_RedInputField = new FloatField { value = m_ChannelMixer.outRed.x }; m_RedInputField.RegisterCallback <ChangeEvent <double>, int>(OnChangeInputField, 0); redSliderPanel.Add(m_RedInputField); Add(redSliderPanel); var greenSliderPanel = new VisualElement { name = "sliderPanel" }; greenSliderPanel.Add(new Label("G")); Action <float> changedGreenIn = (s) => { OnChangeSlider(s, 1); }; m_GreenSlider = new Slider(m_Minimum, m_Maximum, changedGreenIn); greenSliderPanel.Add(m_GreenSlider); m_GreenInputField = new FloatField { value = m_ChannelMixer.outRed.y }; m_GreenInputField.RegisterCallback <ChangeEvent <double>, int>(OnChangeInputField, 1); greenSliderPanel.Add(m_GreenInputField); Add(greenSliderPanel); var blueSliderPanel = new VisualElement { name = "sliderPanel" }; blueSliderPanel.Add(new Label("B")); Action <float> changedBlueIn = (s) => { OnChangeSlider(s, 2); }; m_BlueSlider = new Slider(m_Minimum, m_Maximum, changedBlueIn); blueSliderPanel.Add(m_BlueSlider); m_BlueInputField = new FloatField { value = m_ChannelMixer.outRed.z }; m_BlueInputField.RegisterCallback <ChangeEvent <double>, int>(OnChangeInputField, 2); blueSliderPanel.Add(m_BlueInputField); Add(blueSliderPanel); m_Initialized = true; ResetSliders(); }