com.soviby.unity.ui.ugui-to.../Assets/Editor/Entity/PrefabEntity.cs
2024-12-10 18:14:38 +08:00

79 lines
2.5 KiB
C#

#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using UguiToolkit;
using UguiToolkit.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
namespace UguiToolkit.Editor
{
public class PrefabEntity : BaseEntity<Transform, LayoutInfo.PrefabInfo>
{
protected override void OnApplyTransform(Transform tf)
{
var position = ElementInfo.Position;
tf.position = StageManager.Instance.PrefabContentsRoot.transform.TransformPoint(new Vector3(position.x, position.y, 0));
}
public override void InitPreview()
{
// 创建预制体
var asset = GetPrefabAsset(GetCommonDirPath());
if (asset) {
var go = PrefabUtility.InstantiatePrefab(asset, transform) as GameObject;
EntityHelper.UpdateHierarchyAndSceneVisibilityOfEntity(false, go);
go.name = asset.name;
var _tf = go.transform;
_tf.localPosition = Vector3.zero;
_tf.localRotation = Quaternion.identity;
_tf.localScale = Vector3.one;
}
ApplyTransform(transform);
}
protected override void OnApplyData(Transform ui)
{
ApplyTransform(ui);
}
public GameObject GetPrefabAsset(string commonDirPath)
{
var elementInfo = ElementInfo;
var guids = AssetDatabase.FindAssets(elementInfo.prefabName, new string[] { commonDirPath });
if (guids.Length > 0)
{
return AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GUIDToAssetPath(guids[0]));
}
else
{
Debug.LogError($"[PrefabInfo.GetPrefabPath] 通用组件{elementInfo.prefabName} 不存在 {commonDirPath}");
return null;
}
}
public static bool IsPrefab(GameObject asset)
{
return PrefabUtility.IsAnyPrefabInstanceRoot(asset);
}
public static bool IsCommonPrefab(GameObject asset)
{
var setting = GlobalManager.Instance.setting;
return PrefabUtility.IsAnyPrefabInstanceRoot(asset) && PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(asset).StartsWith(setting.commonPrefabForUIDirPath);
}
public static string GetCommonDirPath()
{
var setting = GlobalManager.Instance.setting;
return setting.commonPrefabForUIDirPath;
}
}
}
#endif