NG_/Assets/Scripts/UI/全局/TextFollower.cs

40 lines
1.4 KiB
C#
Raw Permalink Normal View History

2024-12-13 19:40:05 +08:00
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
// 文本跟随
public class TextFollower : MonoBehaviour
{
public TextMeshProUGUI largeText; // 大文本对象
public TextMeshProUGUI smallText; // 小文本对象
public float offsetX = 0f; // X轴偏移量
public float offsetY = 0f; // Y轴偏移量
private RectTransform largeTextRectTransform; // 大文本的RectTransform
private RectTransform smallTextRectTransform; // 小文本的RectTransform
void Start()
{
// 获取RectTransform
largeTextRectTransform = largeText.GetComponent<RectTransform>();
smallTextRectTransform = smallText.GetComponent<RectTransform>();
}
void Update()
{
// 获取大文本内容的实际尺寸(包括文本的长度)
float largeTextWidth = largeText.preferredWidth; // 获取大文本内容的实际宽度
// 获取大文本的位置
Vector3 largeTextPosition = largeTextRectTransform.position;
// 计算小文本应该放置的位置。小文本应该位于大文本内容的末尾。
// 注意:偏移量是基于大文本内容的宽度来确定的
Vector3 smallTextPosition = largeTextPosition + new Vector3(largeTextWidth+offsetX, offsetY, 0); // 水平跟随
// 设置小文本的位置
smallTextRectTransform.position = smallTextPosition;
}
}