This commit is contained in:
2024-10-16 00:03:41 +08:00
commit 897058435c
5033 changed files with 1009728 additions and 0 deletions

View File

@@ -0,0 +1,175 @@
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace IcecreamView.Editor
{
[CustomEditor(typeof(IcecreamView.IC_AbstractView), true), CanEditMultipleObjects]
public class GameViewAbstractEditor : UnityEditor.Editor
{
public static Texture2D GetTexture2D(Color32 color32)
{
Texture2D texturesss = new Texture2D(4, 4);
Color32[] colors = texturesss.GetPixels32();
for (int i = 0; i < colors.Length; i++)
{
colors[i] = color32;
}
texturesss.SetPixels32(colors);
texturesss.Apply();
return texturesss;
}
public override void OnInspectorGUI()
{
GUIStyle gUIStyle = new GUIStyle();
gUIStyle.fontSize = 20;
gUIStyle.normal.textColor = Color.black;
gUIStyle.normal.background = GameViewAbstractEditor.GetTexture2D(new Color32(0, 205, 255, 100));
gUIStyle.alignment = TextAnchor.MiddleCenter;
gUIStyle.margin = new RectOffset(0, 0, 10, 0);
GUILayout.Space(10);
GUILayout.Box(" Game View ", gUIStyle);
gUIStyle = new GUIStyle();
gUIStyle.fontSize = 16;
gUIStyle.normal.textColor = Color.white;
gUIStyle.normal.background = GameViewAbstractEditor.GetTexture2D(new Color32(77, 77, 77, 255));
gUIStyle.alignment = TextAnchor.MiddleCenter;
GUILayout.Box(this.target.GetType().Name, gUIStyle);
EditorGUILayout.HelpBox("游戏界面基础组件", MessageType.None);
GUILayout.Space(10);
gUIStyle = null;
base.DrawDefaultInspector();
this.serializedObject.ApplyModifiedProperties();
}
}
[CustomEditor(typeof(IcecreamView.IC_ModuleConnector), true), CanEditMultipleObjects]
public class GameViewModuleConnectorEditor : UnityEditor.Editor
{
private bool _isCreate;
private SerializedProperty defaultStory;
private SerializedProperty hasFocus;
private SerializedProperty hasAutoCreate;
private void OnEnable()
{
this.RefreshCreateType();
}
private void RefreshCreateType()
{
if (!EditorApplication.isPlaying)
{
var path = $"Assets/{IceCreamCodeUtils.GlobalInstance.FilePath ?? "Scripts/View"}";
var fileName = $"{serializedObject.targetObject.name.Replace(" ", "")}.cs";
this._isCreate = !File.Exists(path + "/" + fileName);
}
this.defaultStory = this.serializedObject.FindProperty("DefaultStory");
this.hasFocus = this.serializedObject.FindProperty("hasFocusView");
this.hasAutoCreate = this.serializedObject.FindProperty("HasAutoCreate");
}
public override void OnInspectorGUI()
{
GUIStyle gUIStyle = new GUIStyle();
gUIStyle.fontSize = 20;
gUIStyle.normal.textColor = Color.black;
gUIStyle.normal.background = GameViewAbstractEditor.GetTexture2D(new Color32(255, 0, 99, 100));
gUIStyle.alignment = TextAnchor.MiddleCenter;
gUIStyle.margin = new RectOffset(0, 0, 10, 0);
GUILayout.Space(10);
GUILayout.Box(" Game View Connect ", gUIStyle);
EditorGUILayout.HelpBox("模块管理器,用于关联并激活该对象上的所有< Game View Module >", MessageType.None);
GUILayout.Space(10);
if (this._isCreate && hasAutoCreate != null)
{
hasAutoCreate.boolValue = GUILayout.Toggle(hasAutoCreate.boolValue, "自动构建检查", "Button");
if (hasAutoCreate.boolValue)
{
if (GUILayout.Button("自动构建"))
{
IceCreamCodeUtils.CreateCode(this.serializedObject);
this._isCreate = false;
}
}
}
GUILayout.Space(10);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(defaultStory, new GUIContent("UI默认层级"));
EditorGUILayout.PropertyField(hasFocus, new GUIContent("是否拥有焦点"));
EditorGUILayout.EndHorizontal();
gUIStyle = null;
this.serializedObject.ApplyModifiedProperties();
}
}
[CustomEditor(typeof(IcecreamView.IC_AbstractModule), true), CanEditMultipleObjects]
public class GameViewAbstractModuleEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
GUIStyle gUIStyle = new GUIStyle();
gUIStyle.fontSize = 20;
gUIStyle.normal.textColor = Color.black;
gUIStyle.normal.background = GameViewAbstractEditor.GetTexture2D(new Color32(147, 255, 0, 100));
gUIStyle.alignment = TextAnchor.MiddleCenter;
gUIStyle.margin = new RectOffset(0, 0, 10, 0);
GUILayout.Space(10);
GUILayout.Box(" Game View Module ", gUIStyle);
gUIStyle = new GUIStyle();
gUIStyle.fontSize = 16;
gUIStyle.normal.textColor = Color.white;
gUIStyle.normal.background = GameViewAbstractEditor.GetTexture2D(new Color32(77, 77, 77, 255));
gUIStyle.alignment = TextAnchor.MiddleCenter;
GUILayout.Box(this.target.GetType().Name, gUIStyle);
EditorGUILayout.HelpBox("界面功能模块组件,允许多模块自由组合", MessageType.None);
GUILayout.Space(10);
gUIStyle = null;
base.DrawDefaultInspector();
this.serializedObject.ApplyModifiedProperties();
}
}
// public static class IceViewConfigTool{
// [MenuItem("Assets/Create/IceCreamView/AutoView Config", false, 88)]
// public static void CreatConfig() {
// Object[] arr = Selection.GetFiltered(typeof(IC_AbstractView), SelectionMode.TopLevel);
// var GameConfig = ScriptableObject.CreateInstance<IC_ViewConfig>();
// List<IC_ViewInfo> gameInfos = new List<IC_ViewInfo>();
// foreach (var item in arr)
// {
// var a = new IC_ViewInfo();
// a.View = (IC_AbstractView)item;
// a.Table = item.name;
// gameInfos.Add(a);
// }
// GameConfig.GameViewList = gameInfos;
// GameConfig.ConfigName = "defaultConfig";
// if (arr.Length > 0) {
// var filePath = AssetDatabase.GetAssetPath(arr[0]).Replace(arr[0].name + ".prefab", "viewConfig.asset");
// AssetDatabase.CreateAsset(GameConfig, filePath);
// Debug.LogFormat("Create Config : {0}" , filePath);
// }
// AssetDatabase.Refresh();
// }
// }
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9c4773dc9ceb0a4499a573fdb0b3cdcd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,94 @@
using UnityEngine;
using UnityEditor;
using System.Text;
using System.IO;
namespace IcecreamView.Editor
{
public static class IceCreamCodeTemplateEditor
{
private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D);
[MenuItem("Assets/Create/IceCreamView/IceCream ViewModule C# Script", false, 89)]
private static void CreateViewModuleCode()
{
string[] guids = AssetDatabase.FindAssets("ViewAbstractModuleTemplate.cs");
if (guids.Length == 0)
{
Debug.LogError("ViewAbstractModuleTemplate.cs.txt not found in asset database");
return;
}
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
CreateFromTemplate("NewViewModule.cs", path);
}
[MenuItem("Assets/Create/IceCreamView/IceCream View C# Script", false, 89)]
private static void CreateViewCode()
{
string[] guids = AssetDatabase.FindAssets("ViewAbstractTemplate.cs");
if (guids.Length == 0)
{
Debug.LogError("ViewAbstractTemplate.cs.txt not found in asset database");
return;
}
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
CreateFromTemplate("NewView.cs", path);
}
public static void CreateFromTemplate(string initialName, string templatePath)
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
0,
ScriptableObject.CreateInstance<DoCreateCodeFile>(),
initialName,
scriptIcon,
templatePath
);
}
public class DoCreateCodeFile : UnityEditor.ProjectWindowCallback.EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
Object o = CreateScript(pathName, resourceFile);
ProjectWindowUtil.ShowCreatedAsset(o);
}
}
public static UnityEngine.Object CreateScript(string pathName, string templatePath)
{
string className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
string templateText = string.Empty;
UTF8Encoding encoding = new UTF8Encoding(true, false);
if (File.Exists(templatePath))
{
StreamReader reader = new StreamReader(templatePath);
templateText = reader.ReadToEnd();
reader.Close();
templateText = templateText.Replace("#SCRIPTNAME#", className);
templateText = templateText.Replace("#NOTRIM#", string.Empty);
StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
writer.Write(templateText);
writer.Close();
AssetDatabase.ImportAsset(pathName);
return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
}
else
{
Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
return null;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b40b12afaefaa874c8ddfe4e223822f2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,309 @@
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace IcecreamView.Editor
{
public static class IceCreamCodeUtils
{
public const string Templete = @"using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using IcecreamView;
#NamespaceStart
public class #ScriptName : #Abstract
{
public override void OnOpenView(IC_ViewData parameters)
{
}
public override void OnCloseView()
{
}
}
#NamespaceEnd
";
public const string UIPanelTemplete = @"
using IcecreamView;
#NamespaceStart
public class UIPanel
{
//Code start
//Code end
}
#NamespaceEnd
";
public static void CreateCode(SerializedObject target)
{
if (target.targetObject == null || string.IsNullOrEmpty(target.targetObject.name))
{
return;
}
// CodeCompileUnit unit = new CodeCompileUnit();
// //设置命名空间(这个是指要生成的类的空间)
// CodeNamespace myNamespace = new CodeNamespace("Joh.Test");
// //导入必要的命名空间引用
// myNamespace.Imports.Add(new CodeNamespaceImport("System"));
// myNamespace.Imports.Add(new CodeNamespaceImport("UnityEngine"));
// //Code:代码体
// CodeTypeDeclaration myClass = new CodeTypeDeclaration(className);
string className = string.IsNullOrEmpty(GlobalInstance.NameSpacePath) ? target.targetObject.name : GlobalInstance.NameSpacePath + "." + target.targetObject.name;
string objPath = GetGameObjectPath(((IC_ModuleConnector) target.targetObject).transform);
WriteFile("Temp", "ICE_ACTION.tmp", StringToArrayByteUtf8(className + "#" + objPath));
string path = $"Assets/{GlobalInstance.FilePath ?? "Scripts/View"}";
string fileName = $"{target.targetObject.name.Replace(" ", "")}.cs";
if (!File.Exists(path + "/" + fileName))
{
//创建代码
string fileContent = Templete;
if (string.IsNullOrEmpty(GlobalInstance.NameSpacePath) == false)
{
fileContent = fileContent.Replace("#NamespaceStart", $"namespace {GlobalInstance.NameSpacePath}" + "{");
fileContent = fileContent.Replace("#NamespaceEnd", "}");
}
else
{
fileContent = fileContent.Replace("#NamespaceStart", "");
fileContent = fileContent.Replace("#NamespaceEnd", "");
}
fileContent = fileContent.Replace("#Abstract", GlobalInstance.AbstractClass ?? "IC_AbstractModule");
fileContent = fileContent.Replace("#ScriptName", target.targetObject.name);
WriteFile(path, fileName, StringToArrayByteUtf8(fileContent));
Debug.Log("构建UI代码完成" + path + "/" + fileName);
UpdateUIPanel(target.targetObject.name.Replace(" ", ""));
AssetDatabase.Refresh();
}
else
{
// Debug.Log("已存在相同文件名:" + path + "/" + fileName);
BindComponent();
}
}
//
// [MenuItem("Icecream/UpdatePanel")]
// public static void MainTest()
// {
// UpdateUIPanel("Test");
// }
/// <summary>
/// 更新UIPanel
/// </summary>
public static void UpdateUIPanel(String name)
{
var path = GlobalInstance.FilePath;
var fileName = "UIPanel.cs";
if (!File.Exists("Assets/" + path + "/" + fileName))
{
CreateUIPanel();
}
var fileContent = ReadFile("Assets/" + path, fileName);
// Debug.Log(fileContent);
var startIndex = fileContent.IndexOf("//Code start", StringComparison.Ordinal) + 13;
var endIndex = fileContent.IndexOf("//Code end", StringComparison.Ordinal) - 10;
var panelContent = fileContent.Substring(startIndex , endIndex - startIndex);
// Debug.Log(panelContent);
var panelList = panelContent.Split(';');
List<String> panelNames = new List<string>();
var temp = "public const string ";
bool isCreate = true;
foreach (var panel in panelList)
{
var start = panel.IndexOf(temp, StringComparison.Ordinal);
if (start > 0)
{
var p2 = panel.Substring(start + temp.Length);
var panelName = p2.Substring(0, p2.IndexOf(" ", StringComparison.Ordinal));
panelNames.Add(panelName);
if (panelName.Equals(name , StringComparison.Ordinal))
{
isCreate = false;
}
}
}
if (isCreate)
{
//添加新Panel
fileContent = fileContent.Insert(endIndex, $"\r\n {temp}{name} \t\t\t=\"{name}\";");
Debug.Log("构建UIPanel完成: " + name);
}
// Debug.Log(fileContent);
WriteFile("Assets/"+path, fileName, StringToArrayByteUtf8(fileContent));
}
public static void CreateUIPanel()
{
var path = "Assets/" + GlobalInstance.FilePath;
var fileName = "UIPanel.cs";
// if (File.Exists(path + "/" + fileName))
// {
// File.Delete(path + "/" + fileName);
// }
var fileContent = UIPanelTemplete;
if (string.IsNullOrEmpty(GlobalInstance.NameSpacePath) == false)
{
fileContent = fileContent.Replace("#NamespaceStart", $"namespace {GlobalInstance.NameSpacePath}" + "{");
fileContent = fileContent.Replace("#NamespaceEnd", "}");
}
else
{
fileContent = fileContent.Replace("#NamespaceStart", "");
fileContent = fileContent.Replace("#NamespaceEnd", "");
}
WriteFile(path, fileName, StringToArrayByteUtf8(fileContent));
}
[UnityEditor.Callbacks.DidReloadScripts]
public static void BindComponent()
{
if (File.Exists("Temp/ICE_ACTION.tmp") == false)
{
return;
}
string fileContent = ReadFile("Temp", "ICE_ACTION.tmp");
File.Delete("Temp/ICE_ACTION.tmp");
string className = fileContent.Substring(0, fileContent.IndexOf("#", StringComparison.Ordinal));
string objPath = fileContent.Substring(fileContent.IndexOf("#", StringComparison.Ordinal) + 1);
var assembly = Assembly.Load(GlobalInstance.AssemblyName);
if (assembly == null)
{
Debug.LogError("加载失败:" + GlobalInstance.AssemblyName);
return;
}
Type t = assembly.GetType(className);
var obj = GameObject.Find(objPath);
if (t != null)
{
if (!obj.GetComponent(t))
{
obj.gameObject.AddComponent(t);
}
var prefabPath = "Assets/" + GlobalInstance.PrefabsPath + "/" + obj.name + ".prefab";
if (Directory.Exists("Assets/" + GlobalInstance.PrefabsPath) == false)
{
Directory.CreateDirectory("Assets/" + GlobalInstance.PrefabsPath);
}
if (File.Exists(prefabPath))
{
//保存修改到预制体
PrefabUtility.ApplyPrefabInstance(obj, InteractionMode.AutomatedAction);
}
else
{
//创建预制体
PrefabUtility.SaveAsPrefabAssetAndConnect(obj, prefabPath, InteractionMode.AutomatedAction);
}
Debug.Log("构建UI预制体完成" + prefabPath);
AssetDatabase.Refresh();
}
}
private static string GetGameObjectPath(Transform obj)
{
Transform selectChild = obj;
string result = selectChild.name;
if (selectChild != null)
{
while (selectChild.parent != null)
{
selectChild = selectChild.parent;
result = string.Format("{0}/{1}", selectChild.name, result);
}
}
return result;
// Debug.Log(string.Format("The gameobject:{0}'s path has been copied to the clipboard!", obj.name));
}
private static IC_GlobalSetting _globalInstance;
public static IC_GlobalSetting GlobalInstance
{
get
{
if (_globalInstance == null)
{
#if UNITY_EDITOR
_globalInstance = AssetDatabase.LoadAssetAtPath<IC_GlobalSetting>("Assets/IceCreamGlobalSettings.asset");
if (_globalInstance == null)
{
_globalInstance = ScriptableObject.CreateInstance<IC_GlobalSetting>();
// 自定义资源保存路径
string path = "Assets/";
//如果项目总不包含该路径,创建一个
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
AssetDatabase.CreateAsset(_globalInstance, path + "/IceCreamGlobalSettings.asset");
AssetDatabase.Refresh();
_globalInstance = AssetDatabase.LoadAssetAtPath<IC_GlobalSetting>("Assets/IceCreamGlobalSettings.asset");
}
#endif
}
return _globalInstance;
}
}
public static void WriteFile(string path, string fileName, byte[] content)
{
CreateDirectory(path);
var fullName = path + "/" + fileName;
FileStream fs = new FileStream(fullName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.None);
fs.Write(content, 0, content.Length);
fs.Close();
}
public static void CreateDirectory(string path)
{
if (!(Directory.Exists(path) || File.Exists(path)))
{
Directory.CreateDirectory(path);
}
}
public static string ReadFile(string path, string fileName)
{
var fullName = path + "/" + fileName;
if (Directory.Exists(path) || File.Exists(path))
{
FileStream fs = new FileStream(fullName, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.None);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
return ArrayByteUtf8ToString(bytes);
}
return null;
}
public static byte[] StringToArrayByteUtf8(string value) { return Encoding.UTF8.GetBytes(value); }
public static string ArrayByteUtf8ToString(byte[] bytes) { return Encoding.UTF8.GetString(bytes); }
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2f0314c9fd814f96be2fccf7d0394189
timeCreated: 1588241337

View File

@@ -0,0 +1,16 @@
{
"name": "IcecreamView.Editor",
"references": [
"IcecreamView"
],
"optionalUnityReferences": [],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": []
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4eee1f27bc1848f41ac762647e3912f6
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 052ea4d2fafb5aa4c823e3d039f49584
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,23 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using IcecreamView;
public class #SCRIPTNAME# : IC_AbstractModule
{
public override void OnInitView()
{
}
public override void OnOpenView(Dictionary<string,IC_ViewData> parameters)
{
}
public override void OnCloseView()
{
}
public override void OnDestroyView()
{
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 240f6fdcb40695640889bf682044b199
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,23 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using IcecreamView;
public class #SCRIPTNAME# : IC_AbstractView
{
public override void OnInitView()
{
}
public override void OnOpenView(Dictionary<string,IC_ViewData> parameters)
{
}
public override void OnCloseView()
{
}
public override void OnDestroyView()
{
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9395976db8255cb41880384900ea4460
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f06a3c4cf0626b44d92e09b68c9cc508
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,400 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using IcecreamView;
using IcecreamView.Editor;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UIElements;
using Object = System.Object;
namespace IcecreamView
{
public class IceCreamUIBox : EditorWindow
{
private Label _viewTitle;
private Label _viewDesc;
private VisualElement _customUIInfo;
private VisualElement _customUIWork;
private VisualElement _createInfo;
private VisualElement _createWork;
private Label _customUITitle;
private Label _customUIDesc;
private Button _createBtn;
private IC_ModuleConnector connector;
private CanvasNode _baseCanvasNode;
//---------------------------create work------------------------------------
private Button _loadUISceneBtn;
private Label _createSceneInfoLabel;
private Label _createSceneInfoDesc;
private ListView _createPanelListView;
private TextField _createPanelName;
private SliderInt _createPanelLayer;
private Toggle _createPanelToggle;
private Button _createPanelCreateBtn;
// private Label
//---------------------------create work------------------------------------
private Transform _onSelectionTransform;
[MenuItem("IceCream/IceCream UI Box")]
public static void ShowBoxTool()
{
IceCreamUIBox wnd = GetWindow<IceCreamUIBox>();
wnd.titleContent = new GUIContent("IceCream UI Box");
}
public void CreateGUI()
{
// Debug.Log("创建 IceCream UI Box");
// return;
UnityEditor.Selection.selectionChanged += OnSelectionChangeScene;
VisualElement root = rootVisualElement;
var fromScriptableObject = MonoScript.FromScriptableObject(this);
var path = AssetDatabase.GetAssetPath(fromScriptableObject);
//将指定的path改为同路径下后缀为.uxml的路径
path = path.Replace(".cs", ".uxml");
var window = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(path);
if (window == null)
{
Debug.LogError("无法加载uxml文件 " + path + " 请检查插件是否损坏!");
return;
}
VisualElement container = window.Instantiate();
_customUIInfo = container.Q<VisualElement>("BoxViewInfo");
_customUIWork = container.Q<VisualElement>("BoxViewCustom");
_createInfo = container.Q<VisualElement>("BoxPanelInfo");
_createWork = container.Q<VisualElement>("BoxPanelCreate");
_viewTitle = _customUIInfo.Q<Label>("ViewTitle");
_viewDesc = _customUIInfo.Q<Label>("Desc");
_createBtn = _customUIWork.Q<Button>("CreateBtn");
_customUITitle = _customUIWork.Q<Label>("CustomUITitle");
_customUIDesc = _customUIWork.Q<Label>("CustomUIDesc");
var uxmlButton = _customUIInfo.Q<Button>("UpdateViewBtn");
_loadUISceneBtn = _createInfo.Q<Button>("LoadSceneBtn");
_createSceneInfoLabel = _createInfo.Q<Label>("ViewTitle");
_createSceneInfoDesc = _createInfo.Q<Label>("Desc");
_createPanelName = _createWork.Q<TextField>("PanelName");
_createPanelLayer = _createWork.Q<SliderInt>("PanelLayer");
_createPanelToggle = _createWork.Q<Toggle>("FocusToggle");
_createPanelCreateBtn = _createWork.Q<Button>("CreateBtn");
_createPanelListView = _createWork.Q<ListView>("CustomUiListView");
uxmlButton.RegisterCallback<MouseUpEvent>(OnClick_UpdateViewInfo);
_createBtn.RegisterCallback<MouseUpEvent>(OnClick_Create);
_loadUISceneBtn.RegisterCallback<MouseUpEvent>(OnClick_LoadUIScene);
_createPanelCreateBtn.RegisterCallback<MouseUpEvent>(OnClick_CreatePanel);
_createPanelListView.onSelectionChange += OnPanelItemSelected;
_customUIInfo.SetEnabled(false);
root.Add(container);
UpdateCustomUiView();
}
private CustomUIPanelConfig curSelectPanelPrefab;
private void OnPanelItemSelected(IEnumerable<object> obj)
{
var enumerable = obj as object[] ?? obj.ToArray();
if (enumerable.Length == 0)
{
_createWork.SetEnabled(false);
return;
}
curSelectPanelPrefab = enumerable[0] as CustomUIPanelConfig;
_createWork.SetEnabled(true);
_createPanelCreateBtn.SetEnabled(true);
_createPanelName.SetEnabled(true);
_createPanelLayer.SetEnabled(true);
_createPanelToggle.SetEnabled(true);
// ReSharper disable once UsePatternMatching
var config = curSelectPanelPrefab;
if (config != null)
{
_createPanelName.SetValueWithoutNotify(config.Name);
_createPanelLayer.value = config.Prefab.PanelLayer;
_createPanelToggle.value = config.Prefab.HasFocusView;
}
}
private void OnClick_CreatePanel(MouseUpEvent evt)
{
if (curSelectPanelPrefab == null || curSelectPanelPrefab.Prefab == null)
{
Debug.LogError("待创建对象为空,无法创建!");
return;
}
var curCanvasNode = Selection.activeTransform.GetComponent<CanvasNode>() ?? _baseCanvasNode;
//构建到场景
var obj = (MonoBehaviour)PrefabUtility.InstantiatePrefab(curSelectPanelPrefab.Prefab,
curCanvasNode.transform);
var instantiatePrefab = obj.GetComponent<RectTransform>();
instantiatePrefab.anchoredPosition = Vector2.zero;
PrefabUtility.UnpackPrefabInstance(obj.gameObject, PrefabUnpackMode.Completely,
InteractionMode.AutomatedAction);
var icModuleConnector = instantiatePrefab.GetComponent<IC_ModuleConnector>();
// var serializedObject = new SerializedObject(icModuleConnector.gameObject);
// var sortOrder = serializedObject.FindProperty("SortOrder");
// sortOrder.intValue = _createPanelLayer.value;
// var hasFocusView = serializedObject.FindProperty("hasFocusView");
// hasFocusView.boolValue = _createPanelToggle.value;
var pl = icModuleConnector.GetType();
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var sortOrder = pl.GetField("DefaultStory" , bindingFlags);
var hasFocusView = pl.GetField("hasFocusView" , bindingFlags);
sortOrder?.SetValue(icModuleConnector , _createPanelLayer.value);
hasFocusView?.SetValue(icModuleConnector , _createPanelToggle.value);
icModuleConnector.name = _createPanelName.value;
Selection.activeTransform = obj.transform;
// EditorUtility.SetDirty(icModuleConnector);
// EditorSceneManager.SaveOpenScenes();
}
private void OnClick_LoadUIScene(MouseUpEvent evt)
{
var globalInstanceUiSceneAsset = IceCreamCodeUtils.GlobalInstance.UiSceneAsset;
if (globalInstanceUiSceneAsset != null)
{
EditorSceneManager.SaveOpenScenes();
EditorSceneManager.OpenScene(AssetDatabase.GetAssetPath(globalInstanceUiSceneAsset));
UpdateCustomUiView();
}
}
private void ShowWork(int state)
{
_createInfo.style.display = new StyleEnum<DisplayStyle>(state == 0 ? DisplayStyle.Flex : DisplayStyle.None);
_createWork.style.display = new StyleEnum<DisplayStyle>(state == 0 ? DisplayStyle.Flex : DisplayStyle.None);
_customUIInfo.style.display =
new StyleEnum<DisplayStyle>(state == 1 ? DisplayStyle.Flex : DisplayStyle.None);
_customUIWork.style.display =
new StyleEnum<DisplayStyle>(state == 1 ? DisplayStyle.Flex : DisplayStyle.None);
}
private void OnSelectionChangeScene()
{
UpdateCustomUiView();
}
private void UpdateCustomUiView()
{
var activeTransform = UnityEditor.Selection.activeTransform;
if (activeTransform == null)
{
ShowWork(-1);
rootVisualElement.SetEnabled(false);
return;
}
rootVisualElement.SetEnabled(true);
// Debug.Log("当前选中" + activeTransform.name);
//根据当前选中的物体获取对应的View通过方向遍历父节点查找挂载了IC_ModuleConnector的物体如果找到则显示对应的信息
connector = null;
var target = activeTransform;
while (target != null && target != target.root)
{
if (target.TryGetComponent(out connector))
{
_onSelectionTransform = activeTransform;
break;
}
target = target.parent;
}
if (connector != null)
{
ShowWork(1);
UpdateCustomWork();
}
else
{
ShowWork(0);
UpdateCreateWork();
// _baseCanvasNode
}
}
private void UpdateCustomWork()
{
//更新ViewTitle
_viewTitle.text = $"当前根页面:" + (connector != null ? connector.name : "无");
_viewDesc.text = $"页面层级:{(connector != null ? connector.PanelLayer : 0)}";
if (_currentSelected == null)
{
_customUITitle.text = "";
_customUIDesc.text = "";
_createBtn.SetEnabled(false);
}
ShowList();
}
private void UpdateCreateWork()
{
var canvasNodes = Transform.FindObjectsOfType<CanvasNode>();
if (canvasNodes != null && canvasNodes.Length > 0)
{
_baseCanvasNode = canvasNodes[0];
}
var isShowLoadBtn = _baseCanvasNode == null && IceCreamCodeUtils.GlobalInstance.UiSceneAsset != null;
_loadUISceneBtn.style.display =
new StyleEnum<DisplayStyle>((isShowLoadBtn ? DisplayStyle.Flex : DisplayStyle.None));
// ReSharper disable once Unity.NoNullPropagation
var curCanvasNode = Selection.activeTransform.GetComponent<CanvasNode>() ?? _baseCanvasNode;
if (curCanvasNode != null)
{
_createSceneInfoLabel.text = $"当前是否可以进行UI创建 <color=green>{curCanvasNode != null}</color>";
_createSceneInfoDesc.text = $"当前创建节点Canvas{curCanvasNode.name}";
_createWork.SetEnabled(true);
}
else
{
_createSceneInfoLabel.text = $"当前是否可以进行UI创建 <color=red>{curCanvasNode != null}</color>";
_createSceneInfoDesc.text = "";
_createWork.SetEnabled(false);
}
ShowPanelList();
}
private void ShowPanelList()
{
var items = IceCreamCodeUtils.GlobalInstance.CustomPanelConfigs;
if (items == null)
{
items = new List<CustomUIPanelConfig>();
}
Func<VisualElement> makeItem = () => new Label();
Action<VisualElement, int> bindItem = (e, i) => ((Label)e).text = items[i].Name;
_createPanelListView.makeItem = makeItem;
_createPanelListView.bindItem = bindItem;
_createPanelListView.itemsSource = items;
_createPanelListView.selectionType = SelectionType.Single;
_createPanelCreateBtn.SetEnabled(false);
_createPanelName.SetEnabled(false);
_createPanelLayer.SetEnabled(false);
_createPanelToggle.SetEnabled(false);
}
private void ShowList()
{
var items = IceCreamCodeUtils.GlobalInstance.CustomUIConfigs;
if (items == null)
{
items = new List<CustomUIConfig>();
}
Func<VisualElement> makeItem = () => new Label();
Action<VisualElement, int> bindItem = (e, i) => ((Label)e).text = items[i].Name;
var listView = _customUIWork.Q<ListView>("CustomUiListView");
listView.makeItem = makeItem;
listView.bindItem = bindItem;
listView.itemsSource = items;
listView.selectionType = SelectionType.Single;
listView.onSelectionChange += OnItemSelected;
}
private void OnClick_Create(MouseUpEvent evt)
{
if (connector == null)
{
Debug.LogError("当前选中物体没有挂载IC_ModuleConnector组件无法创建");
return;
}
if (_currentSelected == null)
{
Debug.LogError("当前没有选中任何自定义UI无法创建");
return;
}
var config = _currentSelected as CustomUIConfig;
if (config == null || config.Prefab == null)
{
Debug.LogError("当前选中的自定义UI配置有误无法创建");
return;
}
//构建到场景
var obj = (MonoBehaviour)PrefabUtility.InstantiatePrefab(config.Prefab, _onSelectionTransform);
var instantiatePrefab = obj.GetComponent<RectTransform>();
//设置位置,如果父节点是RectTransform则设置为居中
if (_onSelectionTransform is RectTransform)
{
instantiatePrefab.anchoredPosition = Vector2.zero;
}
else
{
instantiatePrefab.localPosition = Vector3.zero;
}
PrefabUtility.UnpackPrefabInstance(obj.gameObject, PrefabUnpackMode.Completely,
InteractionMode.AutomatedAction);
Selection.activeTransform = obj.transform;
Debug.Log("创建成功!");
}
private void OnClick_UpdateViewInfo(MouseUpEvent evt)
{
UpdateCustomUiView();
}
private Object _currentSelected;
private void OnItemSelected(IEnumerable<object> obj)
{
var enumerable = obj as object[] ?? obj.ToArray();
if (enumerable.Length == 0)
{
_customUIInfo.SetEnabled(false);
return;
}
_currentSelected = enumerable[0];
_createBtn.SetEnabled(true);
_customUIInfo.SetEnabled(true);
// ReSharper disable once UsePatternMatching
var config = _currentSelected as CustomUIConfig;
if (config != null)
{
_customUITitle.text = config.Name;
_customUIDesc.text = config.Desc;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1bbc1495191064b45b319b93211dd6e8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,33 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:VisualElement name="BoxPanelInfo" style="height: 108px; background-color: rgba(82, 80, 80, 0.45); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; position: relative; left: 0; right: 0; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120);">
<ui:Label text="当前是否为UI场景" display-tooltip-when-elided="true" name="ViewTitle" tooltip="当前根页面信息" usage-hints="None" style="height: 23px; -unity-font-style: bold; -unity-text-align: middle-left; font-size: 20px; color: rgb(248, 248, 248);" />
<ui:Label text="Label" display-tooltip-when-elided="true" name="Desc" style="height: 43px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; color: rgb(171, 171, 171);" />
<ui:Button text="跳转到UI制作场景" display-tooltip-when-elided="true" name="LoadSceneBtn" style="align-items: center; justify-content: flex-end; -unity-text-align: upper-center; white-space: nowrap; position: relative; top: auto; left: 0; height: 23px; width: auto; -unity-font-style: normal; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; right: 0; bottom: auto; overflow: visible; visibility: visible; display: flex; opacity: 1;" />
</ui:VisualElement>
<ui:VisualElement name="BoxPanelCreate" style="height: 257px; background-color: rgba(82, 80, 80, 0.45); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; position: relative; left: 0; right: 0; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120);">
<ui:Label text="页面构建" display-tooltip-when-elided="true" name="PanelCreateTitle" usage-hints="None" style="height: 23px; -unity-font-style: normal; -unity-text-align: middle-left; font-size: 18px; color: rgb(248, 248, 248);" />
<ui:VisualElement style="height: 2px; background-color: rgb(46, 46, 46); margin-top: 5px; margin-bottom: 5px;" />
<ui:ListView focusable="true" reorderable="false" reorder-mode="Simple" name="CustomUiListView" style="padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; background-color: rgb(63, 63, 63); border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; height: 108px; max-height: 108px;" />
<ui:VisualElement name="CustomUIInfo" style="border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; height: auto; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; justify-content: flex-start; bottom: 0; position: relative; width: auto; left: 0; right: 0; align-items: stretch; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px;">
<ui:TextField picking-mode="Ignore" label="页面名称" text="New Panel" name="PanelName" />
<ui:SliderInt picking-mode="Ignore" label="页面层级" value="0" high-value="100" show-input-field="true" name="PanelLayer" low-value="-50" />
<ui:Toggle label="是否聚焦" name="FocusToggle" value="true" />
<ui:Button text="构建到场景" display-tooltip-when-elided="true" name="CreateBtn" style="white-space: nowrap; align-items: stretch; left: auto; right: auto; justify-content: flex-start; flex-direction: column; flex-wrap: nowrap; transform-origin: center;" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement name="BoxViewInfo" style="height: 108px; background-color: rgba(82, 80, 80, 0.45); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; position: relative; left: 0; right: 0; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); display: none;">
<ui:Label text="当前根页面xxxxx" display-tooltip-when-elided="true" name="ViewTitle" tooltip="当前根页面信息" usage-hints="None" style="height: 23px; -unity-font-style: bold; -unity-text-align: middle-left; font-size: 20px; color: rgb(248, 248, 248);" />
<ui:Label text="Label" display-tooltip-when-elided="true" name="Desc" style="height: 43px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; color: rgb(171, 171, 171);" />
<ui:Button text="刷新" display-tooltip-when-elided="true" name="UpdateViewBtn" style="align-items: center; justify-content: flex-end; -unity-text-align: upper-center; white-space: nowrap; position: relative; top: auto; left: 0; height: 23px; width: auto; -unity-font-style: normal; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; right: 0; bottom: auto; overflow: visible; visibility: visible; display: none; opacity: 1;" />
</ui:VisualElement>
<ui:VisualElement name="BoxViewCustom" style="height: 257px; background-color: rgba(82, 80, 80, 0.45); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; position: relative; left: 0; right: 0; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); display: none;">
<ui:Label text="自定义组件库" display-tooltip-when-elided="true" name="ViewTitle" tooltip="当前根页面信息" usage-hints="None" style="height: 23px; -unity-font-style: normal; -unity-text-align: middle-left; font-size: 18px; color: rgb(248, 248, 248);" />
<ui:VisualElement style="height: 2px; background-color: rgb(46, 46, 46); margin-top: 5px; margin-bottom: 5px;" />
<ui:ListView focusable="true" reorderable="false" reorder-mode="Simple" name="CustomUiListView" style="padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; background-color: rgb(63, 63, 63); border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; height: 108px; max-height: 108px;" />
<ui:VisualElement name="CustomUIInfo" style="border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; height: auto; border-left-color: rgb(120, 120, 120); border-right-color: rgb(120, 120, 120); border-top-color: rgb(120, 120, 120); border-bottom-color: rgb(120, 120, 120); border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; justify-content: flex-start; bottom: 0; position: relative; width: auto; left: 0; right: 0; align-items: stretch; padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 5px;">
<ui:Label text="Label" display-tooltip-when-elided="true" name="CustomUITitle" style="margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; -unity-font-style: bold;" />
<ui:Label text="Label" display-tooltip-when-elided="true" name="CustomUIDesc" style="margin-left: 5px; margin-right: 5px; margin-top: 5px; margin-bottom: 5px; -unity-font-style: normal; color: rgb(168, 168, 168);" />
<ui:Button text="构建到场景" display-tooltip-when-elided="true" name="CreateBtn" style="white-space: nowrap; align-items: stretch; left: auto; right: auto; justify-content: flex-start; flex-direction: column; flex-wrap: nowrap; transform-origin: center;" />
</ui:VisualElement>
</ui:VisualElement>
</ui:UXML>

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 4ec32f900ab7abb4ab911e12724e2dad
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}