using System; using UnityEngine; using UnityEngine.UI; using DG.Tweening; using System.Collections; [RequireComponent(typeof(RectTransform))] public class ChatBulletItem : MonoBehaviour { [SerializeField] RectTransform rectContent; [SerializeField] RichText contentText; [SerializeField] RectTransform rectSys; [SerializeField] RichText sysText; // 背景图左右的额外留白 (x:左边距, y:右边距) [SerializeField] Vector2 padding = new Vector2(50f, 50f); [SerializeField] Vector2 sysPadding = new Vector2(70f, 70f); private RectTransform rectTrans; private GameObject sourcePrefab; private Tweener moveTweener; private Action onFinishCallback; private void Awake() { rectTrans = GetComponent(); } public void Init(bool isSys, string content, ArrayList infoList, Color color, float speed, Vector2 startPos, float leftBoundary, GameObject prefab, Action onFinish) { if (rectTrans == null) rectTrans = GetComponent(); rectContent.SetActive(!isSys); rectSys.SetActive(isSys); if (infoList != null) { contentText.SetExtenalData(infoList); sysText.SetExtenalData(infoList); } contentText.text = content; sysText.text = content; contentText.color = color; sysText.color = color; sourcePrefab = prefab; onFinishCallback = onFinish; // 获取文本内容的理想宽度 //LayoutRebuilder.ForceRebuildLayoutImmediate(contentText.rectTransform); float txtWidth = contentText.preferredWidth; float totalWidth = 0; float currentHeight = 0; if (!isSys) { // 计算背景图的总宽度 = 文本宽 + 左右Padding totalWidth = txtWidth + padding.x + padding.y; // 保持原有的高度 currentHeight = rectTrans.sizeDelta.y; // 设置背景图(ContentImage)的大小 rectContent.sizeDelta = new Vector2(totalWidth, currentHeight); } else { // 计算背景图的总宽度 = 文本宽 + 左右Padding totalWidth = txtWidth + sysPadding.x + sysPadding.y; // 图片的高度 currentHeight = 39; // 设置背景图(ContentImage)的大小 rectSys.sizeDelta = new Vector2(totalWidth, currentHeight); } // 设置根节点的大小 rectTrans.sizeDelta = new Vector2(totalWidth, currentHeight); // 设置初始位置 rectTrans.anchoredPosition = startPos; // 此时 rectTrans.rect.width 已经是我们手动设置的 totalWidth 了 float endX = leftBoundary - totalWidth; float distance = Mathf.Abs(startPos.x - endX); float duration = distance / speed; // 5. 开始移动 moveTweener?.Kill(); moveTweener = rectTrans.DOAnchorPosX(endX, duration) .SetEase(Ease.Linear) .OnComplete(Recycle); } //ChatBulletItem最右侧的X坐标 public float GetRightEdgeX() { return rectTrans.anchoredPosition.x + rectTrans.rect.width; } private void Recycle() { moveTweener?.Kill(); moveTweener = null; onFinishCallback?.Invoke(this); if (GameObjectPoolManager.Instance != null && sourcePrefab != null) { GameObjectPoolManager.Instance.GetPool(sourcePrefab).Release(this.gameObject); } else { Destroy(gameObject); } } private void OnDestroy() { moveTweener?.Kill(); } }