Files
test/Assets/PerfectWorld/Scripts/UI/UIPlayer.cs
2026-02-09 18:07:56 +07:00

125 lines
3.5 KiB
C#

using System;
using CSNetwork.GPDataType;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace BrewMonster.PerfectWorld.Scripts.UI
{
public class UIPlayer : MonoBehaviour
{
[Header("World HUD (optional)")]
public Image healthImage;
[SerializeField] private TextMeshProUGUI nameText;
[SerializeField] private Transform canvasRoot;
[Header("References")]
[SerializeField] private CECPlayer hostplayer;
private const string DefaultLayerName = "Default";
private bool _isVisible;
private void Awake()
{
CacheRefs();
}
private void Start()
{
CacheRefs();
if (hostplayer == null)
{
Debug.LogError("[UIPlayer] CECPlayer not found in parents.");
return;
}
SetVisible(false);
RefreshName();
EventBus.SubscribeChannel<cmd_self_info_00>(hostplayer.m_PlayerInfo.cid, UpdateHostPlayerInfoUI);
}
private void OnDestroy()
{
if (hostplayer == null)
{
return;
}
EventBus.UnsubscribeChannel<cmd_self_info_00>(hostplayer.m_PlayerInfo.cid, UpdateHostPlayerInfoUI);
}
private void UpdateHostPlayerInfoUI(cmd_self_info_00 obj)
{
//healthText.text = $"{obj.iHP}/{obj.iMaxHP}";
if (healthImage != null && obj.iMaxHP > 0)
healthImage.fillAmount = (float)obj.iHP / obj.iMaxHP;
}
public void SetVisible(bool visible)
{
_isVisible = visible;
if (canvasRoot == null)
return;
if (visible)
{
int defaultLayer = LayerMask.NameToLayer(DefaultLayerName);
if (defaultLayer < 0) defaultLayer = 0;
SetLayerRecursively(canvasRoot.gameObject, defaultLayer);
RefreshName();
}
canvasRoot.gameObject.SetActive(visible);
}
public bool IsVisible() => _isVisible;
public void RefreshName()
{
if (nameText == null || hostplayer == null)
return;
var n = hostplayer.GetName();
if (string.IsNullOrWhiteSpace(n))
n = hostplayer.gameObject != null ? hostplayer.gameObject.name : "";
if (!string.IsNullOrWhiteSpace(n))
nameText.text = n;
}
private void CacheRefs()
{
if (hostplayer == null)
hostplayer = GetComponentInParent<CECPlayer>();
if (canvasRoot == null)
{
var t = transform.Find("Canvas");
if (t != null) canvasRoot = t;
}
if (nameText == null)
{
var named = transform.GetComponentsInChildren<TextMeshProUGUI>(true);
foreach (var tmp in named)
{
if (tmp != null && tmp.gameObject.name.Contains("Name", StringComparison.OrdinalIgnoreCase))
{
nameText = tmp;
break;
}
}
}
}
private static void SetLayerRecursively(GameObject obj, int layer)
{
if (obj == null) return;
obj.layer = layer;
var t = obj.transform;
for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer);
}
}
}