using SK.Framework; using System.Collections; using System.Collections.Generic; using System.IO; using TMPro; using UnityEngine; using UnityEngine.UI; public class UIToolDragView : UIView { public Transform categoryParent; public Transform toolParent; public GameObject categoryTogglePrefab; public GameObject toolItemPrefab; public Transform dragLayer; private string rootPath; private string currentModel; void Awake() { rootPath = Path.Combine(Application.dataPath, "Resources/UITool"); Init("模型"); } /// /// 外部调用:设置模型并生成工具类 Toggle /// public void Init(string modelName) { currentModel = modelName; CreateCategoryToggles(); } /// /// 生成工具类 Toggle /// void CreateCategoryToggles() { foreach (Transform c in categoryParent) Destroy(c.gameObject); string modelPath = Path.Combine(rootPath, currentModel); if (!Directory.Exists(modelPath)) { Debug.LogError($"模型目录不存在: {currentModel}"); return; } var classDirs = Directory.GetDirectories(modelPath); Toggle firstToggle = null; foreach (var dir in classDirs) { string toolClassName = Path.GetFileName(dir); Toggle toggle = Instantiate(categoryTogglePrefab, categoryParent).GetComponent(); toggle.GetComponentInChildren().text = toolClassName; toggle.group = categoryParent.GetComponent(); toggle.onValueChanged.AddListener(isOn => { if (isOn) LoadTools(toolClassName); }); if (firstToggle == null) firstToggle = toggle; } // 默认选中第一个 if (firstToggle != null) firstToggle.isOn = true; } /// /// 加载指定工具类下的工具 /// void LoadTools(string toolClass) { foreach (Transform t in toolParent) Destroy(t.gameObject); Debug.Log("加载工具"); string toolPath = Path.Combine(rootPath, currentModel, toolClass); Debug.Log(toolPath); var pngFiles = Directory.GetFiles(toolPath, "*.png"); Debug.Log(pngFiles.Length); foreach (var png in pngFiles) { Debug.Log("加载工具1"); string toolName = Path.GetFileNameWithoutExtension(png); string resPath = $"UITool/{currentModel}/{toolClass}/{toolName}"; Debug.Log($"加载工具{resPath}"); Texture2D tex = Resources.Load(resPath); Sprite sprite = Sprite.Create( tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f) ); //Sprite sprite = Resources.Load(resPath); if (sprite == null) continue; GameObject item = Instantiate(toolItemPrefab, toolParent); item.GetComponent().sprite = sprite; item.transform.Find("name").GetComponent().text = toolName; ToolItemData data = item.AddComponent(); data.category = currentModel; data.group = toolClass; data.toolName = toolName; item.GetComponent().dragLayer=dragLayer; } } }