public void Render() { bool changed = false; if (_groupChildren.arraySize == 0) { EditorGUILayout.HelpBox(@"Add slots and insert controls using drag & drop. Note: controls must be direct children of this component.", MessageType.Info, true); } if (!string.IsNullOrEmpty(_errorMessage)) { GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox(_errorMessage, MessageType.Error, true); if (GUILayout.Button(new GUIContent("Dismiss", TextureCache.Instance.Cancel), StyleCache.Instance.Button, GUILayout.Height(38))) { _errorMessage = null; } GUILayout.EndHorizontal(); } int count = _groupChildren.arraySize; for (int i = 0; i < count; i++) { #region 1 row ComponentAdapter oldAdapter = (ComponentAdapter)_groupChildren.GetArrayElementAtIndex(i).objectReferenceValue; EditorGUILayout.BeginHorizontal(); _oldColor = GUI.color; if (null == oldAdapter) { GUI.color = Color.green; } ComponentAdapter newAdapter = (ComponentAdapter)EditorGUILayout.ObjectField(string.Empty, oldAdapter, typeof(ComponentAdapter), true, GUILayout.ExpandWidth(true)); GUI.color = _oldColor; #endregion #region Button add if (GUILayout.Button(GuiContentCache.Instance.AddItem, StyleCache.Instance.ImageOnlyButton, GUILayout.ExpandWidth(false)))//, StyleCache.Instance.ControlButtonStyle)) { _insertAtIndex = i; changed = true; } #endregion #region Button remove if (GUILayout.Button(GuiContentCache.Instance.RemoveItem, StyleCache.Instance.ImageOnlyButton, GUILayout.ExpandWidth(false))) { _removeAtIndex = i; _doRemove = true; changed = true; } #endregion if (oldAdapter != newAdapter) { if (null != newAdapter) { // only direct children of dialog component if (newAdapter.transform.parent == ((ComponentAdapter)_target).transform) { bool contains = false; var enumerator = _groupChildren.GetEnumerator(); while (enumerator.MoveNext()) { ComponentAdapter adapter = (ComponentAdapter)((SerializedProperty)enumerator.Current).objectReferenceValue; if (adapter == newAdapter) { contains = true; break; } } if (contains) { _errorMessage = "Error: button already assigned at another position"; EditorApplication.Beep(); Debug.LogWarning(_errorMessage); } else { _groupChildren.GetArrayElementAtIndex(i).objectReferenceValue = newAdapter; } } else { _errorMessage = "Error: only the direct children could be assigned as buttons"; EditorApplication.Beep(); Debug.LogWarning(_errorMessage); } } changed = true; } EditorGUILayout.EndHorizontal(); GUILayout.Space(2); } #region Add field _oldColor = GUI.color; GUI.color = Color.green; /* ADD to the end */ ComponentAdapter added = (ComponentAdapter)EditorGUILayout.ObjectField(string.Empty, null, typeof(ComponentAdapter), true, GUILayout.ExpandWidth(true)); if (null != added) { _groupChildren.arraySize++; // YEAH! _groupChildren.GetArrayElementAtIndex(Math.Max(_groupChildren.arraySize - 1, 0)).objectReferenceValue = added; changed = true; } GUI.color = _oldColor; #endregion //if (GUILayout.Button(new GUIContent("Add tools element", TextureCache.Instance.Add), StyleCache.Instance.Button, GUILayout.Height(30)))//, StyleCache.Instance.ControlButtonStyle)) //{ // _groupChildren.arraySize++; // YEAH! // _groupChildren.GetArrayElementAtIndex(Math.Max(_groupChildren.arraySize - 1, 0)).objectReferenceValue = null; //} if (_doRemove) { _doRemove = false; if (EditorApplication.isPlaying) { DoRemove(); } else if (EditorUtility.DisplayDialog("Remove element?", string.Format(@"Are you sure you want to remove tool group element?"), "OK", "Cancel")) { DoRemove(); } } if (_insertAtIndex > -1) { _groupChildren.InsertArrayElementAtIndex(_insertAtIndex); _groupChildren.GetArrayElementAtIndex(_insertAtIndex).objectReferenceValue = null; _insertAtIndex = -1; } if (changed) { //Debug.Log("ToolsGroup group changed!"); System.Collections.Generic.List <ComponentAdapter> adapters = new System.Collections.Generic.List <ComponentAdapter>(); count = _groupChildren.arraySize; for (int i = 0; i < count; i++) { ComponentAdapter adapter = (ComponentAdapter)_groupChildren.GetArrayElementAtIndex(i).objectReferenceValue; if (null != adapter) { adapters.Add(adapter); } } AddHandler(adapters); } }
void InitiateDeleteAllUnused(BuildInfo buildReportToDisplay) { BuildReportTool.AssetList list = buildReportToDisplay.UnusedAssets; BuildReportTool.SizePart[] all = list.All; int filesToDeleteCount = 0; for (int n = 0, len = all.Length; n < len; ++n) { BuildReportTool.SizePart b = all[n]; bool okToDelete = BuildReportTool.Util.IsFileOkForDeleteAllOperation(b.Name); if (okToDelete) { //LogMgr.Ins.LogInfo("added " + b.Name + " for deletion"); ++filesToDeleteCount; } } if (filesToDeleteCount == 0) { const string nothingToDelete = "Take note that for safety, Build Report Tool assets, Unity editor assets, version control metadata, and Unix-style hidden files will not be included for deletion.\n\nYou can force deleting them by selecting them (via the checkbox) and using \"Delete selected\", or simply delete them the normal way in your project view."; EditorApplication.Beep(); EditorUtility.DisplayDialog("Nothing to delete!", nothingToDelete, "Ok"); return; } string plural = ""; if (filesToDeleteCount > 1) { plural = "s"; } EditorApplication.Beep(); if (!EditorUtility.DisplayDialog("Delete?", "Among " + all.Length + " file" + plural + " in your project, " + filesToDeleteCount + " will be deleted.\n\nBuild Report Tool assets themselves, Unity editor assets, version control metadata, and Unix-style hidden files will not be included for deletion. You can force-delete those by selecting them (via the checkbox) and use \"Delete selected\", or simply delete them the normal way in your project view.\n\nDeleting a large number of files may take a long time as Unity will rebuild the project's Library folder.\n\nAre you sure about this?\n\nThe file" + plural + " can be recovered from your " + BuildReportTool.Util.NameOfOSTrashFolder + ".", "Yes", "No")) { return; } List <BuildReportTool.SizePart> newAll = new List <BuildReportTool.SizePart>(); int deletedCount = 0; for (int n = 0, len = all.Length; n < len; ++n) { BuildReportTool.SizePart b = all[n]; bool okToDelete = BuildReportTool.Util.IsFileOkForDeleteAllOperation(b.Name); if (okToDelete) { // delete this if (BuildReportTool.Util.ShowFileDeleteProgress(deletedCount, filesToDeleteCount, b.Name, true)) { return; } BuildReportTool.Util.DeleteSizePartFile(b); ++deletedCount; } else { //LogMgr.Ins.LogInfo("added " + b.Name + " to new list"); newAll.Add(b); } } EditorUtility.ClearProgressBar(); BuildReportTool.SizePart[] newAllArr = newAll.ToArray(); BuildReportTool.SizePart[][] perCategoryUnused = BuildReportTool.ReportGenerator.SegregateAssetSizesPerCategory(newAllArr, buildReportToDisplay.FileFilters); list.Reinit(newAllArr, perCategoryUnused); list.ClearSelection(); string finalMessage = filesToDeleteCount + " file" + plural + " removed from your project. They can be recovered from your " + BuildReportTool.Util.NameOfOSTrashFolder + "."; Debug.LogWarning(finalMessage); EditorApplication.Beep(); EditorUtility.DisplayDialog("Delete successful", finalMessage, "OK"); }
private void OnButtonBarGUI() { if (mode == BranchesMode.Default) { // Delete button // If the current branch is selected, then do not enable the Delete button var disableDelete = selectedNode == null || selectedNode.Type == NodeType.Folder || activeBranchNode == selectedNode; EditorGUI.BeginDisabledGroup(disableDelete); { if (GUILayout.Button(DeleteBranchButton, EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { var selectedBranchName = selectedNode.Name; var dialogMessage = string.Format(DeleteBranchMessageFormatString, selectedBranchName); if (EditorUtility.DisplayDialog(DeleteBranchTitle, dialogMessage, DeleteBranchButton, CancelButtonLabel)) { GitClient.DeleteBranch(selectedBranchName, true).Start(); } } } EditorGUI.EndDisabledGroup(); // Create button GUILayout.FlexibleSpace(); if (GUILayout.Button(CreateBranchButton, EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { targetMode = BranchesMode.Create; } } // Branch name + cancel + create else if (mode == BranchesMode.Create) { GUILayout.BeginHorizontal(); { var createBranch = false; var cancelCreate = false; var cannotCreate = selectedNode == null || selectedNode.Type == NodeType.Folder || !Validation.IsBranchNameValid(newBranchName); // Create on return/enter or cancel on escape var offsetID = GUIUtility.GetControlID(FocusType.Passive); if (Event.current.isKey && GUIUtility.keyboardControl == offsetID + 1) { if (Event.current.keyCode == KeyCode.Escape) { cancelCreate = true; Event.current.Use(); } else if (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter) { if (cannotCreate) { EditorApplication.Beep(); } else { createBranch = true; } Event.current.Use(); } } newBranchName = EditorGUILayout.TextField(newBranchName); // Create EditorGUI.BeginDisabledGroup(cannotCreate); { if (GUILayout.Button(NewBranchConfirmButton, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false))) { createBranch = true; } } EditorGUI.EndDisabledGroup(); // Cancel create if (GUILayout.Button(NewBranchCancelButton, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false))) { cancelCreate = true; } // Effectuate create if (createBranch) { GitClient.CreateBranch(newBranchName, selectedNode.Name) .FinallyInUI((success, e) => { if (success) { Redraw(); } else { var errorHeader = "fatal: "; var errorMessage = e.Message.StartsWith(errorHeader) ? e.Message.Remove(0, errorHeader.Length) : e.Message; EditorUtility.DisplayDialog(CreateBranchTitle, errorMessage, Localization.Ok); } }) .Start(); } // Cleanup if (createBranch || cancelCreate) { newBranchName = ""; GUIUtility.keyboardControl = -1; targetMode = BranchesMode.Default; } } GUILayout.EndHorizontal(); } }
/// <summary> /// Creates the copy transform window /// </summary> private void CreateCopyTransformWindow() { //Source transform GUILayout.BeginHorizontal(); GUILayout.Label("Copy from: \t"); source = EditorGUILayout.ObjectField(source, typeof(Transform)) as Transform; GUILayout.EndHorizontal(); EditorGUILayout.Space(); //Position if (GUILayout.Button("Copy Position")) { if (source != null) { foreach (Transform t in Selection.transforms) { Vector3 tmp = new Vector3(); tmp.x = xCheckbox ? source.position.x : t.position.x; tmp.y = yCheckbox ? source.position.y : t.position.y; tmp.z = zCheckbox ? source.position.z : t.position.z; Undo.RegisterUndo(t, "Copy position"); t.position = tmp; } } else { EditorUtility.DisplayDialog("Error", "There is no source transform", "Ok"); EditorApplication.Beep(); } } //Rotation if (GUILayout.Button("Copy Rotation")) { if (source != null) { foreach (Transform t in Selection.transforms) { Vector3 tmp = new Vector3(); tmp.x = xCheckbox ? source.rotation.eulerAngles.x : t.rotation.eulerAngles.x; tmp.y = yCheckbox ? source.rotation.eulerAngles.y : t.rotation.eulerAngles.y; tmp.z = zCheckbox ? source.rotation.eulerAngles.z : t.rotation.eulerAngles.z; Quaternion tmp2 = t.rotation; tmp2.eulerAngles = tmp; Undo.RegisterUndo(t, "Copy rotation"); t.rotation = tmp2; } } else { EditorUtility.DisplayDialog("Error", "There is no source transform", "Ok"); EditorApplication.Beep(); } } //Local Scale if (GUILayout.Button("Copy Local Scale")) { if (source != null) { foreach (Transform t in Selection.transforms) { Vector3 tmp = new Vector3(); tmp.x = xCheckbox ? source.localScale.x : t.localScale.x; tmp.y = yCheckbox ? source.localScale.y : t.localScale.y; tmp.z = zCheckbox ? source.localScale.z : t.localScale.z; Undo.RegisterUndo(t, "Copy local scale"); t.localScale = tmp; } } else { EditorUtility.DisplayDialog("Error", "There is no source transform", "Ok"); EditorApplication.Beep(); } } }
void DrawState(int index) { if (index < 0 || index >= m_Target.groups.Count) { return; } // 在我们的serializedObject中找到States变量 // serializedObject允许我们方便地访问和修改参数,Unity会提供一系列帮助函数。例如,我们可以通过serializedObject来修改组件值,而不是直接修改,Unity会自动创建Undo和Redo功能 SerializedProperty listIterator = serializedObject.FindProperty("groups"); GUILayout.BeginHorizontal(); { // 如果是在实例化的prefab上修改参数,我们可以模仿Unity默认的途径来让修改过的而且未被Apply的值显示成粗体 if (listIterator.isInstantiatedPrefab == true) { //The SetBoldDefaultFont functionality is usually hidden from us but we can use some tricks to //access the method anyways. See the implementation of our own EditorGUIHelper.SetBoldDefaultFont //for more info //EditorGUIHelper.SetBoldDefaultFont(listIterator.GetArrayElementAtIndex(index).prefabOverride); } // BeginChangeCheck()和EndChangeCheck()会检测它们之间的GUI有没有被修改 EditorGUI.BeginChangeCheck(); GUILayout.Label("Id", EditorStyles.label, GUILayout.Width(20)); int id = EditorGUILayout.IntField(m_Target.groups[index].id, GUILayout.Width(40)); GUILayout.Label("num", EditorStyles.label, GUILayout.Width(30)); int num = EditorGUILayout.IntField(m_Target.groups[index].num, GUILayout.Width(40)); GUILayout.Label("refreshTime", EditorStyles.label, GUILayout.Width(80)); float refreshTime = EditorGUILayout.FloatField(m_Target.groups[index].refreshTime, GUILayout.Width(40)); //Vector3 newPosition = EditorGUILayout.Vector3Field("", m_Target.States[index].Position); // 如果修改了的话EndChangeCheck()就会返回true,此时我们就可以进行一些操作例如存储变化的数值 if (EditorGUI.EndChangeCheck()) { //Create an Undo/Redo step for this modification Undo.RecordObject(m_Target, "Modify groups"); m_Target.groups[index].id = id; m_Target.groups[index].num = num; m_Target.groups[index].refreshTime = refreshTime; //m_Target.groups[index].Position = newPosition; // 如果我们直接修改属性,而没有通过serializedObject,那么Unity并不会保存这些数据,Unity只会保存那些标识为dirty的属性 EditorUtility.SetDirty(m_Target); } //EditorGUIHelper.SetBoldDefaultFont(false); if (GUILayout.Button("Remove")) { EditorApplication.Beep(); // 可以很方便的显示一个包含特定按钮的对话框,例如是否同意删除 if (EditorUtility.DisplayDialog("Really?", "Do you really want to remove the enemy ID : " + m_Target.groups[index].id + "?", "Yes", "No") == true) { Undo.RecordObject(m_Target, "Delete groups"); m_Target.groups.RemoveAt(index); EditorUtility.SetDirty(m_Target); } } } GUILayout.EndHorizontal(); }
void SetTCP2Shader(bool useOutline, bool blendedOutline) { var specular = m_WorkflowMode == WorkflowMode.Specular; string shaderPath = null; if (!useOutline) { if (specular) { shaderPath = "Toony Colors Pro 2/Standard PBS (Specular)"; } else { shaderPath = "Toony Colors Pro 2/Standard PBS"; } } else if (blendedOutline) { if (specular) { shaderPath = "Hidden/Toony Colors Pro 2/Standard PBS Outline Blended (Specular)"; } else { shaderPath = "Hidden/Toony Colors Pro 2/Standard PBS Outline Blended"; } } else { if (specular) { shaderPath = "Hidden/Toony Colors Pro 2/Standard PBS Outline (Specular)"; } else { shaderPath = "Hidden/Toony Colors Pro 2/Standard PBS Outline"; } } var shader = Shader.Find(shaderPath); if (shader != null) { if ((m_MaterialEditor.target as Material).shader != shader) { m_MaterialEditor.SetShader(shader, false); } foreach (var obj in m_MaterialEditor.targets) { if (obj is Material) { if (blendedOutline) { (obj as Material).EnableKeyword("OUTLINE_BLENDING"); } else { (obj as Material).DisableKeyword("OUTLINE_BLENDING"); } if (useOutline) { (obj as Material).EnableKeyword("OUTLINES"); } else { (obj as Material).DisableKeyword("OUTLINES"); } } } m_MaterialEditor.Repaint(); SceneView.RepaintAll(); } else { EditorApplication.Beep(); Debug.LogError("Toony Colors Pro 2: Couldn't find the following shader:\n\"" + shaderPath + "\""); } }
void OnGUI() { GUILayout.BeginVertical(); GUILayout.Label("Simulation name:", EditorStyles.boldLabel); GUILayout.Space(10); _simulationName = EditorGUILayout.TextField(_simulationName); GUILayout.EndVertical(); GUILayout.Space(15); GUILayout.BeginVertical(); GUILayout.Label("Domain file:", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); var domain = (TextAsset)EditorGUILayout.ObjectField(_domain, typeof(TextAsset), false); if (EditorGUI.EndChangeCheck()) { if (domain != null) { _domain = domain; } } GUILayout.EndVertical(); GUILayout.BeginVertical(); GUILayout.Label("Problem file:", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); var problem = (TextAsset)EditorGUILayout.ObjectField(_problem, typeof(TextAsset), false); if (EditorGUI.EndChangeCheck()) { if (problem != null) { _problem = problem; } } GUILayout.EndVertical(); GUILayout.Space(15); GUILayout.BeginHorizontal(); if (GUILayout.Button("Create")) { if (_domain == null || _problem == null) { EditorApplication.Beep(); EditorUtility.DisplayDialog("File Missing", "Please Provide Domain And Problem files", "Close"); } else { CreateSimulation(); GUIUtility.ExitGUI(); } } if (GUILayout.Button("Cancel")) { Close(); } GUILayout.EndHorizontal(); }
void OnGUI() { #if UNITY_2018_4_OR_NEWER // Toggle domain reload var playModeOptsEnabled = EditorSettings.enterPlayModeOptionsEnabled; playModeOptsEnabled = EditorGUILayout.Toggle("Disable Domain Reload", playModeOptsEnabled); EditorSettings.enterPlayModeOptionsEnabled = playModeOptsEnabled; #endif if (UnityEngine.Profiling.Profiler.enabled) { EditorGUILayout.LabelField("PROFILER ENABLED"); } allowProfiler = EditorGUILayout.Toggle("Allow profiler", allowProfiler); if (!allowProfiler && UnityEngine.Profiling.Profiler.enabled) { UnityEngine.Profiling.Profiler.enabled = false; } EditorGUILayout.LabelField("Time", Time.realtimeSinceStartup.ToString()); float m1 = (UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / 1024f / 1024f); float m2 = (UnityEngine.Profiling.Profiler.GetAllocatedMemoryForGraphicsDriver() / 1024f / 1024f); float m3 = (UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() / 1024f / 1024f); float m = m1 + m2 + m3; if (m > 10000 && !memoryWarned) { memoryWarned = true; EditorApplication.Beep(); Debug.LogError("Memory over 10000MB!"); allowProfiler = false; UnityEngine.Profiling.Profiler.enabled = false; } if (m < 8000 && memoryWarned) { memoryWarned = false; } EditorGUILayout.LabelField("Memory used:", m.ToString("0.00") + " MB"); isLockReload = EditorGUILayout.Toggle("Lock assembly reload", isLockReload); isAutoSave = EditorGUILayout.Toggle("Auto Save", isAutoSave); EditorGUILayout.LabelField("Full reload", lastReloadTime); EditorGUILayout.LabelField("Compile", lastCompileTime); if (lastAssCompileTime != null) { EditorGUILayout.LabelField("Assembly reload", lastAssCompileTime); } // For mysterious reason, iterating over a dictionary doesn't work, it gets empty! if (lastAssCompile != null) { foreach (string s in lastAssCompile) { var ss = s.Split(':'); EditorGUILayout.LabelField(ss[0], ss[1]); } } if (isLockReload) { if (!isLocked) { Debug.Log("Locking reload of assemblies"); EditorApplication.LockReloadAssemblies(); isLocked = true; } } else { if (isLocked) { Debug.Log("Unlocking reload of assemblies"); EditorApplication.UnlockReloadAssemblies(); isLocked = false; } } }
void OnGUI() { Event e = Event.current; selectedObject = Selection.activeGameObject; if (selectedObject == null) { GUI.color = Color.gray; EditorGUILayout.HelpBox("Select the object...", MessageType.Warning); canDrawView = false; } else { if (selectedObject.GetComponent <MeshFilter>() != null | selectedObject.GetComponent <SkinnedMeshRenderer>() != null) { GUI.color = Color.green; EditorGUILayout.HelpBox("Selected object: " + selectedObject.name, MessageType.None); GUI.color = Color.white; canDrawView = true; if (selectedObject.GetComponent <SkinnedMeshRenderer>() == null) { m = selectedObject.GetComponent <MeshFilter>().sharedMesh; } else { m = selectedObject.GetComponent <SkinnedMeshRenderer>().sharedMesh; } if (m != null) { if (m.uv2.Length > 0) { selectedUV = GUILayout.Toolbar(selectedUV, selectedUVStrings); } else { selectedUV = 0; GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Mesh is not have UV 2. You can generate it", MessageType.None); if (GUILayout.Button("Generate UV2")) { Unwrapping.GenerateSecondaryUVSet(m); EditorApplication.Beep(); EditorUtility.DisplayDialog("Done", "Process is done!", "OK"); } GUILayout.EndHorizontal(); } tris = m.triangles; if (selectedUV == 0) { uvs = m.uv; } else { uvs = m.uv2; } } } else { GUI.color = Color.gray; EditorGUILayout.HelpBox("Object must have a Mesh Filter or Skinned Mesh Renderer", MessageType.Warning); canDrawView = false; } } if (e.mousePosition.x > uvPreviewRect.x & e.mousePosition.x <uvPreviewRect.width + sideSpace& e.mousePosition.y> uvPreviewRect.y & e.mousePosition.y < uvPreviewRect.height + sideSpace + ySpace) { mousePositionInsidePreview = true; } else { mousePositionInsidePreview = false; } if (mousePositionInsidePreview) { if (e.type == EventType.MouseDrag) { xPanShift += e.delta.x; yPanShift += e.delta.y; } if (e.type == EventType.ScrollWheel) { scale += -(e.delta.y * 0.02f); } } uvPreviewRect = new Rect(new Rect(sideSpace, ySpace + sideSpace, uvPreviewWindow.position.width - (sideSpace * 2), uvPreviewWindow.position.height - ySpace - (sideSpace * 2))); GUI.DrawTexture(new Rect(0, 0, uvPreviewWindow.position.width, ySpace), fillTextureGray); if (canDrawView) { GUI.DrawTexture(uvPreviewRect, fillTextureDark); //GRID for (int i = 1; i < 4096; i += (int)(gridStep)) { int x1h = (int)(uvPreviewRect.x - 1); int x2h = (int)(uvPreviewRect.width + sideSpace); int yh = i + (ySpace + sideSpace) - 1; int y1v = ySpace + sideSpace; int y2v = (int)(uvPreviewRect.height + ySpace + sideSpace); int xv = i + sideSpace - 1; if (yh < uvPreviewRect.height + ySpace + sideSpace) { DrawLine(x1h, yh, x2h, yh, new Color(1, 1, 1, 0.15f)); } if (xv < uvPreviewRect.width + sideSpace) { DrawLine(xv, y1v, xv, y2v, new Color(1, 1, 1, 0.15f)); } } //UV for (int i = 0; i < tris.Length; i += 3) { int line1x1 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line1y1 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line1x2 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line1y2 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift + windowDefaultSize); int line2x1 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line2y1 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line2x2 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line2y2 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize; int line3x1 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line3y1 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line3x2 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line3y2 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize; Rect cropRect = new Rect(uvPreviewRect.x, uvPreviewRect.y, uvPreviewRect.width + sideSpace, uvPreviewRect.height + ySpace + sideSpace); DrawLine(line1x1, line1y1, line1x2, line1y2, new Color(0, 1, 1, 1), true, cropRect); DrawLine(line2x1, line2y1, line2x2, line2y2, new Color(0, 1, 1, 1), true, cropRect); DrawLine(line3x1, line3y1, line3x2, line3y2, new Color(0, 1, 1, 1), true, cropRect); } DrawLine(0, ySpace - 1, (int)uvPreviewWindow.position.width, ySpace - 1, Color.gray); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 1); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 2); EditorGUIUtility.AddCursorRect(uvPreviewRect, MouseCursor.Pan); if (GUILayout.Button("Save To PNG")) { UVSaveWindow uvSaveWindow = (UVSaveWindow)EditorWindow.GetWindow(typeof(UVSaveWindow)); uvSaveWindow.title = "Save to PNG"; uvSaveWindow.maxSize = new Vector2(256, 125); uvSaveWindow.minSize = new Vector2(256, 124); uvSaveWindow.uvsToRender = uvs; uvSaveWindow.trianglesToRender = tris; } } Repaint(); }
public static void BeepSound() { #if UNITY_EDITOR EditorApplication.Beep(); #endif }
static void DoBeep() { EditorApplication.Beep(); }
void OnGUI() { Event e = Event.current; selectedObject = Selection.activeGameObject; if (selectedObject == null) { GUI.color = Color.gray; EditorGUILayout.HelpBox("请选择物件...", MessageType.Warning); canDrawView = false; } else { if (selectedObject.GetComponent <MeshFilter>() != null | selectedObject.GetComponent <SkinnedMeshRenderer>() != null) { GUI.color = Color.green; EditorGUILayout.HelpBox("选择的物件: " + selectedObject.name, MessageType.None); GUI.color = Color.white; canDrawView = true; if (selectedObject.GetComponent <SkinnedMeshRenderer>() == null) { m = selectedObject.GetComponent <MeshFilter>().sharedMesh; } else { m = selectedObject.GetComponent <SkinnedMeshRenderer>().sharedMesh; } if (m != null) { GUILayout.BeginHorizontal(); if (m.uv2.Length > 0) { selectedUV = GUILayout.Toolbar(selectedUV, selectedUVStrings); } else { selectedUV = 0; GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Mesh没有第二套UV", MessageType.None); if (GUILayout.Button("生成第二套UV")) { Unwrapping.GenerateSecondaryUVSet(m); EditorApplication.Beep(); EditorUtility.DisplayDialog("完成", "第二套UV已经生成!", "确认"); } GUILayout.EndHorizontal(); } tris = m.triangles; if (selectedUV == 0) { uvs = m.uv; } else { uvs = m.uv2; } } } else { GUI.color = Color.gray; EditorGUILayout.HelpBox("物件必须有Mesh Filter/Skined Mesh Renderer组件", MessageType.Warning); canDrawView = false; } } if (e.mousePosition.x > uvPreviewRect.x & e.mousePosition.x <uvPreviewRect.width + sideSpace& e.mousePosition.y> uvPreviewRect.y & e.mousePosition.y < uvPreviewRect.height + sideSpace + ySpace) { mousePositionInsidePreview = true; } else { mousePositionInsidePreview = false; } if (mousePositionInsidePreview) { if (e.type == EventType.MouseDrag) { xPanShift += e.delta.x; yPanShift += e.delta.y; } if (e.type == EventType.ScrollWheel) { scale += -(e.delta.y * 0.02f); } } uvPreviewRect = new Rect(sideSpace, ySpace + sideSpace, uvPreviewWindow.position.width - (sideSpace * 2), uvPreviewWindow.position.height - ySpace - (sideSpace * 2)); uvSpaceRect = new Rect(sideSpace + xPanShift, (int)(-1 * scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize, scale * windowDefaultSize, scale * windowDefaultSize); GUI.DrawTexture(new Rect(0, 0, uvPreviewWindow.position.width, ySpace), fillTextureGray); if (canDrawView) { GUI.DrawTexture(uvPreviewRect, fillTextureDark); //texture if (texture != null) { GUI.BeginGroup(uvPreviewRect); EditorGUI.DrawPreviewTexture(new Rect(uvSpaceRect.x - uvPreviewRect.x, uvSpaceRect.y - uvPreviewRect.y, uvSpaceRect.width, uvSpaceRect.height), texture); GUI.EndGroup(); //GUI.DrawTexture(uvSpaceRect, texture); } //GRID for (int i = 1; i < 4096; i += (int)(gridStep)) { int x1h = (int)(uvPreviewRect.x - 1); int x2h = (int)(uvPreviewRect.width + sideSpace); int yh = i + (ySpace + sideSpace) - 1; int y1v = ySpace + sideSpace; int y2v = (int)(uvPreviewRect.height + ySpace + sideSpace); int xv = i + sideSpace - 1; if (yh < uvPreviewRect.height + ySpace + sideSpace) { DrawLine(x1h, yh, x2h, yh, new Color(1, 1, 1, 0.15f)); } if (xv < uvPreviewRect.width + sideSpace) { DrawLine(xv, y1v, xv, y2v, new Color(1, 1, 1, 0.15f)); } } //UV for (int i = 0; i < tris.Length; i += 3) { int line1x1 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line1y1 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line1x2 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line1y2 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift + windowDefaultSize); int line2x1 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line2y1 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line2x2 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line2y2 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize; int line3x1 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line3y1 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize; int line3x2 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift); int line3y2 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize; Rect cropRect = new Rect(uvPreviewRect.x, uvPreviewRect.y, uvPreviewRect.width, uvPreviewRect.height); DrawLine(line1x1, line1y1, line1x2, line1y2, new Color(0, 1, 1, 1), true, cropRect); DrawLine(line2x1, line2y1, line2x2, line2y2, new Color(0, 1, 1, 1), true, cropRect); DrawLine(line3x1, line3y1, line3x2, line3y2, new Color(0, 1, 1, 1), true, cropRect); } //uv clamp line { int lbx = (int)(sideSpace + xPanShift); int lby = (int)(ySpace + sideSpace + yPanShift) + windowDefaultSize; int rbx = (int)(scale * windowDefaultSize + sideSpace + xPanShift); int rby = (int)(ySpace + sideSpace + yPanShift) + windowDefaultSize; int ltx = (int)(+sideSpace + xPanShift); int lty = (int)(-scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize; int rtx = (int)(scale * windowDefaultSize + sideSpace + xPanShift); int rty = (int)(-scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize; Rect cropRect = new Rect(uvPreviewRect.x, uvPreviewRect.y, uvPreviewRect.width, uvPreviewRect.height); DrawLine(ltx, lty, rtx, rty, new Color(0, 1, 0, 1), true, cropRect); DrawLine(ltx, lty, lbx, lby, new Color(0, 1, 0, 1), true, cropRect); DrawLine(rtx, rty, rbx, rby, new Color(0, 1, 0, 1), true, cropRect); DrawLine(lbx, lby, rbx, rby, new Color(0, 1, 0, 1), true, cropRect); } DrawLine(0, ySpace - 1, (int)uvPreviewWindow.position.width, ySpace - 1, Color.gray); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 1); DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 2); EditorGUIUtility.AddCursorRect(uvPreviewRect, MouseCursor.Pan); // if(GUILayout.Button("Save To PNG")){ // UVSaveWindow uvSaveWindow = (UVSaveWindow)EditorWindow.GetWindow (typeof (UVSaveWindow)); // uvSaveWindow.title = "Save to PNG"; // uvSaveWindow.maxSize = new Vector2(256,125); // uvSaveWindow.minSize = new Vector2(256,124); // uvSaveWindow.uvsToRender = uvs; // uvSaveWindow.trianglesToRender = tris; // } texture = (Texture2D)EditorGUILayout.ObjectField("选择纹理贴图:", texture, typeof(Texture2D), true); GUILayout.EndHorizontal(); } Repaint(); }
/// <summary> /// Beeps the editor with path print out /// </summary> private static void BeepEditor(string path) { EditorApplication.Beep(); Debug.Log($"<color=cyan>Screenshot saved to {path}</color>"); }
static void Dev_ResetToReport() { ExportManager.CreateReport(); EditorApplication.Beep(); }
private void HandlePasteEvent() { var copyBufferString = EditorGUIUtility.systemCopyBuffer; var elements = copyBufferString.Split(new[] { k_InputAssetMarker }, StringSplitOptions.RemoveEmptyEntries); if (!copyBufferString.StartsWith(k_InputAssetMarker)) { return; } SerializedProperty currentActionMapProperty = null; var selectedActionMap = GetSelectedActionMap(); if (selectedActionMap != null) { currentActionMapProperty = selectedActionMap.elementProperty; } for (var i = 0; i < elements.Length; i++) { var row = elements[i]; if (IsRowOfType <ActionMapTreeItem>(ref row)) { if (m_SerializedObject == null) { throw new InvalidOperationException("Pasting action map is not a valid operation"); } currentActionMapProperty = InputActionSerializationHelpers.AddActionMapFromSavedProperties(m_SerializedObject, GetParameterDictionary(row)); m_Apply(); continue; } if (IsRowOfType <ActionTreeItem>(ref row)) { var newActionProperty = InputActionSerializationHelpers.AddActionFromSavedProperties(GetParameterDictionary(row), currentActionMapProperty); while (i + 1 < elements.Length) { try { var nextRow = elements[i + 1]; if (nextRow.StartsWith(typeof(BindingTreeItem).Name)) { nextRow = nextRow.Substring(typeof(BindingTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeGroupTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeGroupTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeTreeItem).Name.Length); } else { break; } InputActionSerializationHelpers.AddBindingFromSavedProperties(GetParameterDictionary(nextRow), newActionProperty, currentActionMapProperty); i++; } catch (ArgumentException e) { Debug.LogException(e); break; } } m_Apply(); continue; } if (IsRowOfType <BindingTreeItem>(ref row) || IsRowOfType <CompositeGroupTreeItem>(ref row) || IsRowOfType <CompositeTreeItem>(ref row)) { var selectedRow = GetSelectedAction(); if (selectedRow == null) { EditorApplication.Beep(); continue; } selectedRow.AddBindingFromSavedProperties(GetParameterDictionary(row)); m_Apply(); continue; } } }
void CalculateBudget() { // Looping one month at a time for (int Month = 0; Month <= allMonths.Length - 1; Month++) { float thisMonthsAdsIncome = 0; float thisMonthsPremiumSellIncome = 0; float thisMonthSpendOnAcquisition = 0; // Is User acquisition campaign ongoing this month? // Add a months base cost to total cost accumulatedMonthlyBaseCost += allMonths[Month].MonthlyBaseCost; // Looping one day at a time for (int Day = 1; Day <= 30; Day++) { // Count total number of days run, just for checking and maybe later use this for something TotalRunDays++; // Since someone like Google simply has a price for "an install", we say that for the money we budget for a day, we can get this many players for (int i = 0; i < allMonths[Month].DailyAcquisitionBudget / CPI; i++) { // This is adding a Player into the loop NewInstall(); // Tracking how much is actually used on marketing AccumulatedspendOnAcquisition += CPI; thisMonthSpendOnAcquisition += CPI; } if (player.Count > 0) { // A day in an existing players Life inside this loop..-> for (int i = 0; i <= player.Count - 1; i++) { // Breaking out if this model is working with so many loops it might hurt ;D IterationsDone++; if (IterationsDone >= MaxIterations) { Debug.Log("MAX ITERATIONS REACHED - ERROR - CHANGE NUMBERS!!"); txt("MAX ITERATIONS REACHED - ERROR - CHANGE NUMBERS!!"); IterationsDone = 0; break; } // Entering data into the Player player[i].daysHasHadGameInstalled++; // Below we see if the Player is uninstalling or leaving ad revenue stream by buying Premium bool PlayerWillUninstall = false; //------- Making Money if (!player[i].havePurchasedPremium) { // Make money on ads accumulatedEarningsAds += (AdsShownToAUserOnADayPlaying * eCPM / 1000); thisMonthsAdsIncome += (AdsShownToAUserOnADayPlaying * eCPM / 1000);; // This is very much rough guestimate, but we say that if a Player has a general chance of (ever) buying premium, that chance is spread out (over 15 days) if (Random.value < chancesOnePlayerWillEverBuyPremium / 15) { player[i].havePurchasedPremium = true; accumulatedEarningsSellPremium += premiumPrice; thisMonthsPremiumSellIncome += premiumPrice; TotalPremiumsSold++; } } // Review if (Random.value < chancesForAReviewEveryDayFromOnePlayer && !player[i].haveGivenAReview) // This is a rough, here Players only "give reviews" _when they install & chances are for it over their lifetime_, which makes no sense, but is simpler to set numbers up for ;) { numberOfReviews++; player[i].haveGivenAReview = true; // one Player leads to another extra chance because this an active messager if (Random.value < chancesForOneOrganicSpreadEveryDayForOnePlayer) { OrganicInstall(); } } // Organic / Viral spread if (Random.value < chancesForOneOrganicSpreadEveryDayForOnePlayer) { OrganicInstall(); } // Based on known general metrics of 1, 7 and 30 days retention // we rough it out with hard cut days like that, when a potential uninstall takes place // instead of a less transparent (though realistic) curve of when players uninstall //------- Uninstalling if (player[i].daysHasHadGameInstalled == 1) { if (Random.value < dayOneRetention) { PlayerWillUninstall = true; } } if (player[i].daysHasHadGameInstalled == 7) { if (Random.value < daySevenRetention) { PlayerWillUninstall = true; } } if (player[i].daysHasHadGameInstalled == 30) { if (Random.value < OneMonthRetention) { PlayerWillUninstall = true; } } if (PlayerWillUninstall) { player.Remove(player[i]); } } } } if (DumpDataIntoAFile) { float accumulatedResult = (accumulatedEarningsAds + accumulatedEarningsSellPremium) - (accumulatedMonthlyBaseCost + AccumulatedspendOnAcquisition); addMonthToCSV(Month, player.Count, Mathf.Round(accumulatedEarningsAds), Mathf.Round(thisMonthsPremiumSellIncome), Mathf.Round((accumulatedResult)), Mathf.Round(thisMonthSpendOnAcquisition), Mathf.Round(allMonths[Month].MonthlyBaseCost)); accumulatedEarningsAds = 0; thisMonthsPremiumSellIncome = 0; thisMonthSpendOnAcquisition = 0; } TotalRunMonths = Month; } txt(" "); txt("Statistics:"); txt("-----------------"); txt("Project months: " + TotalRunMonths); txt("Project Days: " + TotalRunDays); txt("Total installs over time, disregarding later uninstalls: " + TotalPlayersInstalled); txt("Active Players At End of model run: " + player.Count); txt("Reviews in appstore: " + numberOfReviews); txt("Organic/viral Spread: " + organicSpread + " installs"); txt(" "); txt("Income:"); txt("-----------------"); txt("Ads income: " + accumulatedEarningsAds); txt("Premiums Income: " + accumulatedEarningsSellPremium + " (Sold: " + TotalPremiumsSold + " of price: " + premiumPrice + ") "); txt("Total income : " + (accumulatedEarningsSellPremium + accumulatedEarningsAds)); txt(" "); txt("Spendings:"); txt("-----------------"); txt("Acummulated Spend on user acquisition: -" + AccumulatedspendOnAcquisition); txt("Acummulated Base costs: -" + accumulatedMonthlyBaseCost); txt("Total costs: -" + (accumulatedMonthlyBaseCost + AccumulatedspendOnAcquisition)); txt(" "); txt(" "); txt("Result Total: " + ((accumulatedEarningsAds + accumulatedEarningsSellPremium) - (accumulatedMonthlyBaseCost + AccumulatedspendOnAcquisition))); txt("====================================================="); txt(" "); txt(" "); txt(" "); txt(" "); txt("Iterations done: " + IterationsDone); EditorApplication.Beep(); CsvReadWrite(); }
private void DeleteSelectedRows() { var rows = GetSelectedRows().ToArray(); var rowTypes = rows.Select(r => r.GetType()).Distinct().ToList(); // Don't allow to delete different types at once because it's hard to handle. if (rowTypes.Count() > 1) { EditorApplication.Beep(); return; } // Remove composite bindings foreach (var compositeGroup in FindRowsToDeleteOfType <CompositeGroupTreeItem>(rows)) { var action = (compositeGroup.parent as ActionTreeItem); for (var i = compositeGroup.children.Count - 1; i >= 0; i--) { var composite = (CompositeTreeItem)compositeGroup.children[i]; action.RemoveBinding(composite.index); } action.RemoveBinding(compositeGroup.index); } // Remove bindings foreach (var bindingRow in FindRowsToDeleteOfType <BindingTreeItem>(rows)) { var action = bindingRow.parent as ActionTreeItem; action.RemoveBinding(bindingRow.index); } // Remove actions foreach (var actionRow in FindRowsToDeleteOfType <ActionTreeItem>(rows)) { var action = actionRow; ActionMapTreeItem actionMap; if (m_Tree != null) { actionMap = actionRow.parent as ActionMapTreeItem; } else { actionMap = m_ActionMapsTree.GetSelectedActionMap(); } var bindingsCount = InputActionSerializationHelpers.GetBindingCount(actionMap.bindingsProperty, action.actionName); for (var i = bindingsCount - 1; i >= 0; i--) { action.RemoveBinding(i); } actionMap.DeleteAction(actionRow.index); } //Remove action maps foreach (var mapRow in FindRowsToDeleteOfType <ActionMapTreeItem>(rows)) { if (m_SerializedObject == null) { throw new InvalidOperationException("Deleting action map is not a valid operation"); } InputActionSerializationHelpers.DeleteActionMap(m_SerializedObject, mapRow.index); } SetEmptySelection(); m_Apply(); }
public static void FireAlarm() { OpenWindow(); EditorApplication.Beep(); ClearData(); }
//-------------------------------------- // PUBLIC METHODS //-------------------------------------- //-------------------------------------- // GET/SET //-------------------------------------- //-------------------------------------- // EVENTS //-------------------------------------- //-------------------------------------- // PRIVATE METHODS //-------------------------------------- private static void ShowError(string msg) { EditorApplication.Beep(); EditorUtility.DisplayDialog("Texture Packer", msg, "Okay"); }
void HandlePasteEvent() { var json = EditorGUIUtility.systemCopyBuffer; var elements = json.Split(new[] { kInputAssetMarker }, StringSplitOptions.RemoveEmptyEntries); if (!json.StartsWith(kInputAssetMarker)) { return; } for (var i = 0; i < elements.Length; i++) { var row = elements[i]; if (IsRowOfType <ActionMapTreeItem>(ref row)) { var map = JsonUtility.FromJson <InputActionMap>(row); InputActionSerializationHelpers.AddActionMapFromObject(m_SerializedObject, map); m_Window.Apply(); continue; } if (IsRowOfType <ActionTreeItem>(ref row)) { var action = JsonUtility.FromJson <InputAction>(row); var actionMap = m_TreeView.GetSelectedActionMap(); var newActionProperty = actionMap.AddActionFromObject(action); while (i + 1 < elements.Length) { try { var nextRow = elements[i + 1]; if (nextRow.StartsWith(typeof(BindingTreeItem).Name)) { nextRow = nextRow.Substring(typeof(BindingTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeGroupTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeGroupTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeTreeItem).Name.Length); } else { break; } var binding = JsonUtility.FromJson <InputBinding>(nextRow); InputActionSerializationHelpers.AppendBindingFromObject(binding, newActionProperty, actionMap.elementProperty); i++; } catch (ArgumentException e) { Debug.LogException(e); break; } } m_Window.Apply(); continue; } if (IsRowOfType <BindingTreeItem>(ref row) || IsRowOfType <CompositeGroupTreeItem>(ref row) || IsRowOfType <CompositeTreeItem>(ref row)) { var binding = JsonUtility.FromJson <InputBinding>(row); var selectedRow = m_TreeView.GetSelectedAction(); if (selectedRow == null) { EditorApplication.Beep(); continue; } selectedRow.AppendBindingFromObject(binding); m_Window.Apply(); continue; } } }
private void LoadCurrentConfigFromShader(Shader shader) { ShaderImporter shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter; string[] features; string[] flags; string[] customData; Dictionary <string, string> keywords; TCP2_ShaderGeneratorUtils.ParseUserData(shaderImporter, out features, out flags, out keywords, out customData); if (features != null && features.Length > 0 && features[0] == "USER") { mCurrentConfig = new TCP2_Config(); mCurrentConfig.ShaderName = shader.name; mCurrentConfig.Filename = System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(shader)); mCurrentConfig.Features = new List <string>(features); mCurrentConfig.Flags = (flags != null) ? new List <string>(flags) : new List <string>(); mCurrentConfig.Keywords = (keywords != null) ? new Dictionary <string, string>(keywords) : new Dictionary <string, string>(); mCurrentShader = shader; mConfigChoice = mUserShadersLabels.IndexOf(shader.name); mDirtyConfig = false; AutoNames(); mCurrentHash = mCurrentConfig.ToHash(); mIsModified = false; if (customData != null && customData.Length > 0) { foreach (string data in customData) { //Hash if (data.Length > 0 && data[0] == 'h') { string dataHash = data; string fileHash = TCP2_ShaderGeneratorUtils.GetShaderContentHash(shaderImporter); if (!string.IsNullOrEmpty(fileHash) && dataHash != fileHash) { mIsModified = true; } } //Timestamp else { ulong timestamp; if (ulong.TryParse(data, out timestamp)) { if (shaderImporter.assetTimeStamp != timestamp) { mIsModified = true; } } } } } } else { EditorApplication.Beep(); this.ShowNotification(new GUIContent("Invalid shader loaded: it doesn't seem to have been generated by the TCP2 Shader Generator!")); mCurrentShader = null; NewShader(); } }
void HandleCopyEvent() { if (!CanCopySelection()) { EditorGUIUtility.systemCopyBuffer = null; EditorApplication.Beep(); return; } var selectedRows = m_TreeView.GetSelectedRows(); var rowTypes = selectedRows.Select(r => r.GetType()).Distinct().ToList(); // Don't allow to copy different type. It will hard to handle pasting if (rowTypes.Count() > 1) { EditorGUIUtility.systemCopyBuffer = null; EditorApplication.Beep(); return; } var copyList = new StringBuilder(kInputAssetMarker); foreach (var selectedRow in selectedRows) { copyList.Append(selectedRow.GetType().Name); copyList.Append(selectedRow.SerializeToString()); copyList.Append(kInputAssetMarker); if (selectedRow is ActionTreeItem && selectedRow.children != null && selectedRow.children.Count > 0) { var action = selectedRow as ActionTreeItem; foreach (var child in action.children) { copyList.Append(child.GetType().Name); copyList.Append((child as BindingTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); // Copy composites if (child.hasChildren) { foreach (var innerChild in child.children) { copyList.Append(innerChild.GetType().Name); copyList.Append((innerChild as BindingTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); } } } } if (selectedRow is CompositeGroupTreeItem && selectedRow.children != null && selectedRow.children.Count > 0) { var composite = selectedRow as CompositeGroupTreeItem; foreach (var child in composite.children) { if (!(child is CompositeTreeItem)) { continue; } copyList.Append(child.GetType().Name); copyList.Append((child as CompositeTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); } } } EditorGUIUtility.systemCopyBuffer = copyList.ToString(); }
/// <summary> /// Creates the Align transform window /// </summary> private void CreateAlignTransformWindow() { //Source transform GUILayout.BeginHorizontal(); GUILayout.Label("Align to: \t"); source = EditorGUILayout.ObjectField(source, typeof(Transform)) as Transform; GUILayout.EndHorizontal(); string[] texts = new string[4] { "Min", "Max", "Center", "Pivot" }; //Display align options EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); GUILayout.Label("Selection:", EditorStyles.boldLabel); alignSelectionOption = GUILayout.SelectionGrid(alignSelectionOption, texts, 1); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); GUILayout.Label("Source:", EditorStyles.boldLabel); alignSourceOption = GUILayout.SelectionGrid(alignSourceOption, texts, 1); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); //Position if (GUILayout.Button("Align")) { if (source != null) { //Add a temporary box collider to the source if it doesn't have one Collider sourceCollider = source.GetComponent <Collider>(); bool destroySourceCollider = false; if (sourceCollider == null) { sourceCollider = source.gameObject.AddComponent <BoxCollider>(); destroySourceCollider = true; } foreach (Transform t in Selection.transforms) { //Add a temporary box collider to the transform if it doesn't have one Collider transformCollider = t.GetComponent <Collider>(); bool destroyTransformCollider = false; if (transformCollider == null) { transformCollider = t.gameObject.AddComponent <BoxCollider>(); destroyTransformCollider = true; } Vector3 sourceAlignData = new Vector3(); Vector3 transformAlignData = new Vector3(); //Transform switch (alignSelectionOption) { case 0: //Min transformAlignData = transformCollider.bounds.min; break; case 1: //Max transformAlignData = transformCollider.bounds.max; break; case 2: //Center transformAlignData = transformCollider.bounds.center; break; case 3: //Pivot transformAlignData = transformCollider.transform.position; break; } //Source switch (alignSourceOption) { case 0: //Min sourceAlignData = sourceCollider.bounds.min; break; case 1: //Max sourceAlignData = sourceCollider.bounds.max; break; case 2: //Center sourceAlignData = sourceCollider.bounds.center; break; case 3: //Pivot sourceAlignData = sourceCollider.transform.position; break; } Vector3 tmp = new Vector3(); tmp.x = xCheckbox ? sourceAlignData.x - (transformAlignData.x - t.position.x) : t.position.x; tmp.y = yCheckbox ? sourceAlignData.y - (transformAlignData.y - t.position.y) : t.position.y; tmp.z = zCheckbox ? sourceAlignData.z - (transformAlignData.z - t.position.z) : t.position.z; //Register the Undo Undo.RegisterUndo(t, "Align " + t.gameObject.name + " to " + source.gameObject.name); t.position = tmp; //Ugly hack! //Unity needs to update the collider of the selection to it's new position //(it stores in cache the collider data) //We can force the update by a change in a public variable (shown in the inspector), //then a call SetDirty to update the collider (it won't work if all inspector variables are the same). //But we want to restore the changed property to what it was so we do it twice. transformCollider.isTrigger = !transformCollider.isTrigger; EditorUtility.SetDirty(transformCollider); transformCollider.isTrigger = !transformCollider.isTrigger; EditorUtility.SetDirty(transformCollider); //Destroy the collider we added if (destroyTransformCollider) { DestroyImmediate(transformCollider); } } //Destroy the collider we added if (destroySourceCollider) { DestroyImmediate(sourceCollider); } } else { EditorUtility.DisplayDialog("Error", "There is no source transform", "Ok"); EditorApplication.Beep(); } } }
static void DEV_ResetReport() { CSVManager.CreateReport(); EditorApplication.Beep(); Debug.Log("The report has been reset... "); }
void InitiateDeleteSelectedInAssetList(BuildInfo buildReportToDisplay, BuildReportTool.AssetList listToDeleteFrom) { if (listToDeleteFrom.IsNothingSelected) { return; } BuildReportTool.SizePart[] all = listToDeleteFrom.All; int numOfFilesRequestedToDelete = listToDeleteFrom.GetSelectedCount(); int numOfFilesToDelete = numOfFilesRequestedToDelete; int systemDeletionFileCount = 0; int brtFilesSelectedForDelete = 0; // filter out files that shouldn't be deleted // and identify unrecoverable files for (int n = 0, len = all.Length; n < len; ++n) { BuildReportTool.SizePart b = all[n]; bool isThisFileToBeDeleted = listToDeleteFrom.InSumSelection(b); if (isThisFileToBeDeleted) { if (BuildReportTool.Util.IsFileInBuildReportFolder(b.Name) && !BuildReportTool.Util.IsUselessFile(b.Name)) { //LogMgr.Ins.LogInfo("BRT file? " + b.Name); --numOfFilesToDelete; ++brtFilesSelectedForDelete; } else if (BuildReportTool.Util.HaveToUseSystemForDelete(b.Name)) { ++systemDeletionFileCount; } } } if (numOfFilesToDelete <= 0) { if (brtFilesSelectedForDelete > 0) { EditorApplication.Beep(); EditorUtility.DisplayDialog("Can't delete!", "Take note that for safety, Build Report Tool assets themselves will not be included for deletion.", "OK"); } return; } // prepare warning message for user bool deletingSystemFilesOnly = (systemDeletionFileCount == numOfFilesToDelete); bool deleteIsRecoverable = !deletingSystemFilesOnly; string plural = ""; if (numOfFilesToDelete > 1) { plural = "s"; } string message = null; if (numOfFilesRequestedToDelete != numOfFilesToDelete) { message = "Among " + numOfFilesRequestedToDelete + " file" + plural + " requested to be deleted, only " + numOfFilesToDelete + " will be deleted."; } else { message = "This will delete " + numOfFilesToDelete + " asset" + plural + " in your project."; } // add warning about BRT files that are skipped if (brtFilesSelectedForDelete > 0) { message += "\n\nTake note that for safety, " + brtFilesSelectedForDelete + " file" + ((brtFilesSelectedForDelete > 1) ? "s" : "") + " found to be Build Report Tool assets are not included for deletion."; } // add warning about unrecoverable files if (systemDeletionFileCount > 0) { if (deletingSystemFilesOnly) { message += "\n\nThe deleted file" + plural + " will not be recoverable from the " + BuildReportTool.Util.NameOfOSTrashFolder + ", unless you have your own backup."; } else { message += "\n\nAmong the " + numOfFilesToDelete + " file" + plural + " for deletion, " + systemDeletionFileCount + " will not be recoverable from the " + BuildReportTool.Util.NameOfOSTrashFolder + ", unless you have your own backup."; } message += "\n\nThis is a limitation in Unity and .NET code. To ensure deleting will move the files to the " + BuildReportTool.Util.NameOfOSTrashFolder + " instead, delete your files the usual way using your project view."; } else { message += "\n\nThe deleted file" + plural + " can be recovered from your " + BuildReportTool.Util.NameOfOSTrashFolder + "."; } message += "\n\nDeleting a large number of files may take a long time as Unity will rebuild the project's Library folder.\n\nProceed with deleting?"; EditorApplication.Beep(); if (!EditorUtility.DisplayDialog("Delete?", message, "Yes", "No")) { return; } List <BuildReportTool.SizePart> allList = new List <BuildReportTool.SizePart>(all); List <BuildReportTool.SizePart> toRemove = new List <BuildReportTool.SizePart>(all.Length / 4); // finally, delete the files int deletedCount = 0; for (int n = 0, len = allList.Count; n < len; ++n) { BuildReportTool.SizePart b = allList[n]; bool okToDelete = BuildReportTool.Util.IsUselessFile(b.Name) || !BuildReportTool.Util.IsFileInBuildReportFolder(b.Name); if (listToDeleteFrom.InSumSelection(b) && okToDelete) { // delete this if (BuildReportTool.Util.ShowFileDeleteProgress(deletedCount, numOfFilesToDelete, b.Name, deleteIsRecoverable)) { return; } BuildReportTool.Util.DeleteSizePartFile(b); toRemove.Add(b); ++deletedCount; } } EditorUtility.ClearProgressBar(); // refresh the asset lists allList.RemoveAll(i => toRemove.Contains(i)); BuildReportTool.SizePart[] allWithRemoved = allList.ToArray(); // recreate per category list (maybe just remove from existing per category lists instead?) BuildReportTool.SizePart[][] perCategoryOfList = BuildReportTool.ReportGenerator.SegregateAssetSizesPerCategory(allWithRemoved, buildReportToDisplay.FileFilters); listToDeleteFrom.Reinit(allWithRemoved, perCategoryOfList); listToDeleteFrom.ClearSelection(); // print info about the delete operation to console string finalMessage = deletedCount + " file" + plural + " removed from your project."; if (deleteIsRecoverable) { finalMessage += " They can be recovered from your " + BuildReportTool.Util.NameOfOSTrashFolder + "."; } EditorApplication.Beep(); EditorUtility.DisplayDialog("Delete successful", finalMessage, "OK"); Debug.LogWarning(finalMessage); }
private void DoAssetsUI() { GUILayout.Space(10); //scan button row GUILayout.BeginVertical(GUI.skin.GetStyle("Box"), GUILayout.Width(_overallWidth - 20)); //the extensions filter, comma separated GUILayout.BeginHorizontal(); { GUI.skin.label.alignment = TextAnchor.MiddleRight; GUILayout.Label("Extensions to scan:"); GUI.skin.label.alignment = TextAnchor.MiddleLeft; GUI.color = Color.white; _extensionsFilter = GUILayout.TextField(_extensionsFilter, GUILayout.MinWidth(200)); GUI.color = _paleGreen; } GUILayout.EndHorizontal(); GUI.skin.button.alignment = TextAnchor.MiddleCenter; GUILayout.BeginHorizontal(); { if (GUILayout.Button("(1) Scan Assets Used In Most Recent Build")) { BeginUsedAssetsFromLogRoutine(); } bool showScanButton = (_assetScanRoutine == null && _usedAssetList.Count > 0); GUI.color = showScanButton ? _paleGreen : Color.grey; if (GUILayout.Button("(2) Scan all Assets in Selected Folder") && showScanButton) { BeginAssetScanRoutine(); } } GUILayout.EndHorizontal(); GUILayout.EndVertical(); if (_assetsInProject.Count() == 0) { GUILayout.Label("No Results To Show"); return; } if (_killList.Count > 0) { GUI.color = Color.cyan; GUILayout.BeginHorizontal(); GUILayout.Label(""); if (GUILayout.Button("DELETE WITH PREJUDICE", GUILayout.Height(50), GUILayout.Width(200))) { int result = EditorUtility.DisplayDialogComplex("Deleting Assets from Project", "All the assets marked in blue will be permanently deleted. Are you sure?", "Yup: kill em.", "Wait, what? No!", "Aw heck, no!"); if (result == 0) { Debug.Log(result); foreach (var path in _killList) { string originalPath = path.TrimStart('✘'); bool deleted = AssetDatabase.DeleteAsset(originalPath); if (deleted) { _assetsInProject.Remove(path); } else { EditorApplication.Beep(); Debug.LogWarning("Could not delete asset: " + path); } } _killList.Clear(); } } GUILayout.EndHorizontal(); GUI.color = _paleGreen; } GUILayout.BeginHorizontal(); GUI.color = Color.red; GUILayout.Label(""); bool selectAll = GUILayout.Button("all", GUILayout.Width(90)); GUI.color = _paleGreen; GUILayout.EndHorizontal(); _unusedScrollPosition = GUILayout.BeginScrollView(_unusedScrollPosition); foreach (var reportPair in _assetsInProject) { bool unused = reportPair.Key.StartsWith(exx); GUI.color = unused ? Color.red : _paleGreen; GUILayout.BeginHorizontal(); string label = reportPair.Value == null ? "null" : reportPair.Value.name; if (GUILayout.Button(label, GUILayout.Width(_overallWidth * .3f))) { Selection.activeObject = reportPair.Value; } if (Selection.activeObject == reportPair.Value) { GUI.color = Color.yellow; } GUILayout.Label(reportPair.Key); if (_killList.Contains(reportPair.Key)) { GUI.color = Color.cyan; } if (unused && (selectAll || GUILayout.Button("del", GUILayout.Width(50)))) { if (_killList.Contains(reportPair.Key)) { _killList.Remove(reportPair.Key); } else { _killList.Add(reportPair.Key); } } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); }
static void Build(BuilderParams parms) { var cfg = ConfigurationModel.Config; var startTime = DateTime.Now; var scenes = GetScenes(); ProcessChanges(); EnableScenes(scenes); var title = cfg.Title; var buildName = title + parms.suffix; var appName = title; // Ensure the build folder exists var projectFolder = Path.Combine(Path.Combine(UnityEngine.Application.dataPath, ".."), ".."); var buildFolder = Path.Combine(projectFolder, buildName); var buildPath = Path.Combine(buildFolder, appName); Debug.Log("build folder is " + buildFolder); Debug.Log("build path is " + buildPath); var mode = cfg.Mode.ToString(); switch (parms.target) { case BuildTarget.Android: buildPath = string.Format("{0}-{1}-{2}{3}.apk", buildPath, cfg.Version, mode, parms.suffix); break; case BuildTarget.StandaloneWindows64: case BuildTarget.StandaloneWindows: buildPath = buildPath + ".exe"; break; case BuildTarget.StandaloneOSX: buildPath = buildPath + ".app"; break; default: break; } var sceneText = "\n\nScenes:\n• " + string.Join("\n• ", scenes.Select(s => Path.GetFileNameWithoutExtension(s)).ToArray()); var additionalText = ""; if (parms.target == BuildTarget.iOS) { additionalText = "\n\nClose project in XCode!"; } // oh hey this is important info about Android debug signing keys // https://productforums.google.com/forum/#!msg/play/xm3h6Crq8lY/IOWg88XhAgAJ // see also // https://github.com/playgameservices/play-games-plugin-for-unity/issues/1871 if (parms.target == BuildTarget.Android) { if (parms.debugSigning) { additionalText = "\n\nDebug signing key will be used."; PlayerSettings.Android.keystoreName = "Keychain/debug.keystore"; PlayerSettings.Android.keyaliasName = "androiddebugkey"; PlayerSettings.Android.keystorePass = "******"; PlayerSettings.Android.keyaliasPass = "******"; PlayerSettings.keystorePass = "******"; PlayerSettings.keyaliasPass = "******"; } else { additionalText = "\n\nRelease signing key will be used."; PlayerSettings.Android.keystoreName = "Keychain/release.keystore"; PlayerSettings.Android.keyaliasName = "releasekey"; PlayerSettings.Android.keystorePass = "******"; PlayerSettings.Android.keyaliasPass = "******"; PlayerSettings.keystorePass = "******"; PlayerSettings.keyaliasPass = "******"; } if (parms.bundle) { additionalText += "\n\nAn .aab bundle will be built for Google Play distribution."; } else { additionalText += "\n\nAn ARM7 APK will be built for sideloading or UDP distribution."; } } // In automatic mode, skip the confirmation dialog if (!parms.automatic) { if (cfg.mode == ConfigurationMode.Release) { var confirm = EditorUtility.DisplayDialog("Release Build", "Are you ready to make a release build?", "Yes", "No"); if (!confirm) { return; } } var dlgTitle = string.Format("Build {0} ({1})", title, cfg.Mode); var dlgBody = string.Format("Build {0} {1} for {2} ({3})", title, cfg.Version, parms.platformText, cfg.Mode); var proceed = EditorUtility.DisplayDialog(dlgTitle, dlgBody + sceneText + additionalText, "Build", "Cancel"); if (!proceed) { return; } } // Only switch build targets once dev has confirmed the build! EditorUserBuildSettings.SwitchActiveBuildTarget(parms.targetGroup, parms.target); BuildOptions options; switch (unityBuildType.ToLower()) { case "debug": options = BuildOptions.Development | BuildOptions.AllowDebugging | BuildOptions.SymlinkLibraries; break; default: options = BuildOptions.SymlinkLibraries; break; } if (parms.target == BuildTarget.Android) { // Gradle me EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle; //options |= BuildOptions.AcceptExternalModificationsToPlayer; if (parms.bundle) { // Build ARM64 + ARM32 platforms into an .AAB bundle; requires IL2CPP PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7; PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP); EditorUserBuildSettings.buildAppBundle = true; } else { // Build just an ARM7 APK using mono back end instead of IL2CPP; // much faster for testing PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7; PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x); EditorUserBuildSettings.buildAppBundle = false; } PlayerSettings.Android.renderOutsideSafeArea = true; } System.IO.Directory.CreateDirectory(buildFolder); var report = BuildPipeline.BuildPlayer(scenes, Path.GetFullPath(buildPath), parms.target, options); var reportText = report.summary.result.ToString(); if (!string.IsNullOrEmpty(reportText)) { reportText = ": " + reportText + " "; } var elapsedTime = DateTime.Now - startTime; var minutes = elapsedTime.Minutes; var seconds = elapsedTime.Seconds; Debug.LogFormat("Build {0} - {1}: process complete at {2} {3}", title, parms.target.ToString(), DateTime.Now.ToString(), reportText); Debug.LogFormat("Build elapsed time {0}:{1:00}", minutes, seconds); #if UNITY_EDITOR_OSX Process say = new Process(); say.StartInfo.FileName = "say"; say.StartInfo.Arguments = parms.completionMessage; say.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; say.Start(); #else EditorApplication.Beep(); #endif // if there's a post-build action configured, // like starting another build, do it. if (parms.postBuild != null) { parms.postBuild(); } }
private void DrawPreComponents() { if (nodeInfo.prefab == null) { return; } using (var hor = new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent("←", "快速解析"), EditorStyles.toolbarButton, GUILayout.Width(20))) { var component = nodeInfo.prefab.GetComponent <PanelBase>(); if (component == null) { EditorApplication.Beep(); } else { //从旧的脚本解析出 GenCodeUtil.AnalysisComponent(component, components); } } } using (var hor = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("BaseType:", GUILayout.Width(lableWidth)); rule.baseTypeIndex = EditorGUILayout.Popup(rule.baseTypeIndex, GenCodeUtil.supportBaseTypes); if (GUILayout.Button(new GUIContent("update", "更新脚本控件信息"), EditorStyles.miniButton, GUILayout.Width(60))) { var go = nodeInfo.prefab; GenCodeUtil.UpdateScripts(go, components, rule); } } if (preComponentList != null) { preComponentList.DoLayoutList(); } var addRect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, EditorGUIUtility.singleLineHeight); if (addRect.Contains(Event.current.mousePosition)) { if (Event.current.type == EventType.DragUpdated) { if (DragAndDrop.objectReferences.Length > 0) { foreach (var item in DragAndDrop.objectReferences) { if (item is GameObject) { DragAndDrop.visualMode = DragAndDropVisualMode.Move; } } } } else if (Event.current.type == EventType.DragPerform) { if (DragAndDrop.objectReferences.Length > 0) { foreach (var item in DragAndDrop.objectReferences) { if (item is GameObject) { var obj = item as GameObject; var parent = PrefabUtility.GetPrefabParent(obj); if (parent) { obj = parent as GameObject; } var c_item = new ComponentItem(obj); c_item.components = GenCodeUtil.SortComponent(obj); components.Add(c_item); } else if (item is ScriptableObject) { var c_item = new ComponentItem(item as ScriptableObject); components.Add(c_item); } } DragAndDrop.AcceptDrag(); } } } }
//Extract an archive into an array of PackedFile static public PackedFile[] ExtractArchive(string archivePath, string filter = null) { string archive = File.ReadAllText(archivePath); string[] archiveLines = File.ReadAllLines(archivePath); if (archiveLines[0] != "# FunDream_ PACKED SHADERS") { EditorApplication.Beep(); Debug.LogError("[FunDream_ ExtractArchive] Invalid FunDream_ archive:\n" + archivePath); return(null); } //Find offset int offset = archive.IndexOf("###") + 4; if (offset < 20) { Debug.LogError("[FunDream_ ExtractArchive] Invalid FunDream_ archive:\n" + archivePath); return(null); } string tcpRoot = FunDream_Utils.FindReadmePath(); List <PackedFile> packedFilesList = new List <PackedFile>(); for (int line = 1; line < archiveLines.Length; line++) { //Index end, start content parsing if (archiveLines[line].StartsWith("#")) { break; } string[] shaderIndex = archiveLines[line].Split(new string[] { ";" }, System.StringSplitOptions.RemoveEmptyEntries); if (shaderIndex.Length != 3) { EditorApplication.Beep(); Debug.LogError("[FunDream_ ExtractArchive] Invalid format in FunDream_ archive, at line " + line + ":\n" + archivePath); return(null); } //Get data string relativePath = shaderIndex[0]; int start = int.Parse(shaderIndex[1]); int length = int.Parse(shaderIndex[2]); //Get content string content = archive.Substring(offset + start, length); //Skip if file already extracted if (File.Exists(tcpRoot + relativePath)) { continue; } //Filter? if (!string.IsNullOrEmpty(filter)) { string[] filters = filter.Split(new string[] { " " }, System.StringSplitOptions.RemoveEmptyEntries); bool skip = false; foreach (string f in filters) { if (!relativePath.ToLower().Contains(f.ToLower())) { skip = true; break; } } if (skip) { continue; } } //Add File packedFilesList.Add(new PackedFile(relativePath, content)); } return(packedFilesList.ToArray()); }
void DrawControl(int index) { if (index < 0 || index >= mCustomEditor.ControConfig.Count) { return; } GUILayout.Space(5); SerializedObject _serializedObject = new SerializedObject(mCustomEditor); SerializedProperty listIterator = _serializedObject.FindProperty("ControConfig"); GUILayout.BeginHorizontal(); { //GUILayout.Label("Name", EditorStyles.label, GUILayout.Width(50)); EditorGUI.BeginChangeCheck(); string newName = GUILayout.TextField(mCustomEditor.ControConfig[index].ControName, GUILayout.Width(120)); if (EditorGUI.EndChangeCheck()) { //Create an Undo/Redo step for this modification Undo.RecordObject(mCustomEditor, "Modify State"); mCustomEditor.ControConfig[index].ControName = newName; // 如果我们直接修改属性,而没有通过serializedObject,那么Unity并不会保存这些数据,Unity只会保存那些标识为dirty的属性 EditorUtility.SetDirty(mCustomEditor); } if (GUILayout.Button("Remove")) { EditorApplication.Beep(); //// 可以很方便的显示一个包含特定按钮的对话框,例如是否同意删除 if (EditorUtility.DisplayDialog("Really?", "Do you really want to remove the state '" + mCustomEditor.ControConfig[index].ControName + "'?", "Yes", "No") == true) { Undo.RecordObject(mCustomEditor, "Delete State"); mCustomEditor.ControConfig.RemoveAt(index); EditorUtility.SetDirty(mCustomEditor); } } if (GUILayout.Button("添加骨骼", GUILayout.Width(200))) { if (BoneTransform == null) { return; } BoneControlConfig boneControlConfig = new BoneControlConfig(); boneControlConfig.Bonetransform = BoneTransform; boneControlConfig.BoneName = BoneTransform.name; for (int i = 0; i < boneControlConfig.ControAble.Length; i++) { boneControlConfig.ControAble[i] = BoneTransformAble[i]; } mCustomEditor.ControConfig[index].ControBoneLis.Add(boneControlConfig); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); SerializedProperty ControBoneLis = listIterator.GetArrayElementAtIndex(index).FindPropertyRelative("ControBoneLis"); EditorGUILayout.PropertyField(ControBoneLis, true); if (EditorGUI.EndChangeCheck()) { _serializedObject.ApplyModifiedProperties(); } GUILayout.EndHorizontal(); } }