Files
jelito/Assets/jelycho/Code/Player/HUD/ObjectsLabelsVC.cs
2025-07-11 14:40:23 +02:00

83 lines
3.9 KiB
C#

using System;
using System.Collections.Generic;
using RebootKit.Engine.Main;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Pool;
using UnityEngine.UIElements;
namespace RebootReality.jelycho.Player.HUD {
public class ObjectsLabelsVC : MonoBehaviour {
[SerializeField] UIDocument m_Document;
[SerializeField] VisualTreeAsset m_LabelTemplate;
IObjectPool<LabelEntry> m_LabelPool;
readonly List<LabelEntry> m_ActiveLabels = new List<LabelEntry>();
void Awake() {
m_LabelPool = new ObjectPool<LabelEntry>(() => {
LabelEntry entry = new LabelEntry();
entry.Parent = this;
entry.Root = new VisualElement();
entry.Root.style.position = Position.Absolute;
entry.Root.style.visibility = Visibility.Hidden;
entry.Root.style.minWidth = 300;
entry.Root.style.height = 64;
m_LabelTemplate.CloneTree(entry.Root);
entry.Label = entry.Root.Q<Label>("player-hud__object-label");
m_Document.rootVisualElement.Add(entry.Root);
return entry;
},
entry => {
entry.Root.style.visibility = Visibility.Visible;
m_ActiveLabels.Add(entry);
},
entry => {
entry.Root.style.visibility = Visibility.Hidden;
m_ActiveLabels.RemoveSwapBack(entry);
},
entry => {
m_ActiveLabels.RemoveSwapBack(entry);
m_Document.rootVisualElement.Remove(entry.Root);
});
}
void Update() {
foreach (LabelEntry entry in m_ActiveLabels) {
Vector3 worldPosition = entry.TargetTransform.position;
Vector2 screenPosition = RR.MainCamera.WorldToScreenPoint(worldPosition);
entry.Root.style.left = screenPosition.x - entry.Root.contentRect.width * 0.5f;
entry.Root.style.top = Screen.height - screenPosition.y - entry.Root.contentRect.height * 0.5f;
}
}
public IDisposable CreateLabel(Transform targetTransform, string labelText) {
if (targetTransform == null) {
throw new ArgumentNullException(nameof(targetTransform));
}
LabelEntry entry = m_LabelPool.Get();
entry.TargetTransform = targetTransform;
entry.Label.text = labelText;
entry.Root.style.visibility = Visibility.Visible;
return entry;
}
class LabelEntry : IDisposable {
public ObjectsLabelsVC Parent;
public VisualElement Root;
public Label Label;
public Transform TargetTransform;
public void Dispose() {
Parent.m_LabelPool.Release(this);
}
}
}
}