EnergyEfficiencyManagement/Assets/UIView/UIToolDragView/UIToolDragView.cs

120 lines
3.4 KiB
C#

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("模型");
}
/// <summary>
/// 外部调用:设置模型并生成工具类 Toggle
/// </summary>
public void Init(string modelName)
{
currentModel = modelName;
CreateCategoryToggles();
}
/// <summary>
/// 生成工具类 Toggle
/// </summary>
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>();
toggle.GetComponentInChildren<TextMeshProUGUI>().text = toolClassName;
toggle.group = categoryParent.GetComponent<ToggleGroup>();
toggle.onValueChanged.AddListener(isOn =>
{
if (isOn)
LoadTools(toolClassName);
});
if (firstToggle == null)
firstToggle = toggle;
}
// 默认选中第一个
if (firstToggle != null)
firstToggle.isOn = true;
}
/// <summary>
/// 加载指定工具类下的工具
/// </summary>
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<Texture2D>(resPath);
Sprite sprite = Sprite.Create(
tex,
new Rect(0, 0, tex.width, tex.height),
new Vector2(0.5f, 0.5f)
);
//Sprite sprite = Resources.Load<Sprite>(resPath);
if (sprite == null) continue;
GameObject item = Instantiate(toolItemPrefab, toolParent);
item.GetComponent<Image>().sprite = sprite;
item.transform.Find("name").GetComponent<TextMeshProUGUI>().text = toolName;
ToolItemData data = item.AddComponent<ToolItemData>();
data.category = currentModel;
data.group = toolClass;
data.toolName = toolName;
item.GetComponent<ToolDragSpawner>().dragLayer=dragLayer;
}
}
}