Files
aibis-dream/Assets/Scripts/UI/DialogUI/Bubbles/Bubble.cs
T
2025-06-05 22:02:26 +08:00

102 lines
2.8 KiB
C#

using System;
using AibisDream.Framework;
using AibisDream.Kit;
using Febucci.UI.Core;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace AibisDream
{
public class Bubble : MonoBehaviour
{
private TypewriterCore _typewriter;
private TMP_Text _actorName;
private TMP_Text _lineText;
private LayoutElement _layoutElement;
#region 参数
[SerializeField] public ActorRole role;
[SerializeField] public int idx;
[SerializeField] private int maxWidth;
#endregion
public event Action<Bubble> OnDisposed;
public bool IsShowingText => _typewriter.isShowingText;
public void LoadConfig(BubbleSlotData data)
{
InitRefs();
role = data.actorRole;
idx = data.idx;
maxWidth = data.maxWidth;
_actorName.gameObject.SetActive(data.hasActorName);
transform.position = CameraKit.GetScreenPos(data.slotPosition);
}
private void InitRefs()
{
_typewriter = GetComponentInChildren<TypewriterCore>();
_actorName = transform.Find("Actor")?.GetComponent<TMP_Text>();
_typewriter.onTextShowed.AddListener(() => EnumEventSystem.Global.Send(DialogEventEnum.LineShown));
// 获取内容文字
_lineText = _typewriter.GetComponent<TMP_Text>();
_layoutElement = _typewriter.GetComponent<LayoutElement>();
}
public void ShowActorName(CharacterVo characterVo)
{
if (_actorName == null || !_actorName.gameObject.activeInHierarchy) return;
_actorName.text = string.IsNullOrEmpty(characterVo.GetActorName())
? string.Empty
: characterVo.GetActorName();
}
public void ShowLine(string line)
{
_typewriter.TextAnimator.SetText("");
gameObject.SetActive(true);
HandleLayout(line);
_typewriter.ShowText(line);
}
public void SkipLine()
{
if (_typewriter.isShowingText)
{
_typewriter.SkipTypewriter();
}
}
public void Hide()
{
gameObject.SetActive(false);
}
public void Dispose()
{
OnDisposed?.Invoke(this);
}
private void HandleLayout(string line)
{
var width = DialogCanvasManager.Instance.EstimateTextWidth(line, _lineText.fontSize);
if (width > maxWidth)
{
_layoutElement.preferredWidth = maxWidth;
}
else
{
_layoutElement.preferredWidth = -1;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(transform.GetComponent<RectTransform>());
}
}
}