gpt4 book ai didi

c# - 为什么 TextMeshPro 在设置文本后不更新 textBounds?

转载 作者:行者123 更新时间:2023-11-30 22:55:13 24 4
gpt4 key购买 nike

我在悬停时实现了工具提示系统。为此,我使用了 textmeshpro 文本和图像。此图像应该是一个简单的背景,具体取决于文本的长度,它总是不同的。

如果我将鼠标悬停在某个元素上,textmeshpro 文本将被替换。背景图像被移动到元素,大小应根据文本的长度改变:

// Hover over slot in
public void OnPointerEnter(PointerEventData eventData) {
if (currentItem != null) {
Debug.Log("hover over slot item in");
GamePlay.EnableCanvas(GamePlay.GetHoverCanvas());

TextMeshProUGUI txtMeshPro = GamePlay.GetHoverCanvas().GetComponentInChildren<TextMeshProUGUI>();

Debug.Log(currentItem.GetItemDescription(currentItem));
txtMeshPro.text = currentItem.GetItemDescription(currentItem);

var hoverCanvasText = txtMeshPro.GetComponent<RectTransform>();
var hoverCanvasTextBG = GamePlay.GetHoverCanvas().GetComponentInChildren<Image>().GetComponent<RectTransform>();

hoverCanvasText.position = new Vector3(this.GetComponent<RectTransform>().position.x, this.GetComponent<RectTransform>().position.y + 50, 0);

hoverCanvasTextBG.position = new Vector3(this.GetComponent<RectTransform>().position.x, this.GetComponent<RectTransform>().position.y + 50, 0);
hoverCanvasTextBG.sizeDelta = new Vector2(txtMeshPro.textBounds.size.x + 15, txtMeshPro.textBounds.size.y + 15);
// No clue why image is not resized properly on first hover
}
}

我遇到的奇怪问题是,当我第一次将鼠标悬停在该元素上时,图像大小不会改变。

替换文本和更改位置总是没有问题。

问题描述:

首先将鼠标悬停在元素 A 上:图像背景大小根本不会改变。

第二次悬停在元素 B 上:图像背景大小发生变化,但元素 A 的大小正确

第三次悬停在元素 A 上:图像背景大小发生变化,但元素 B 的大小正确

这怎么可能?我不明白这里发生了什么。该代码在位置上没有任何问题,为什么相同的逻辑不适用于尺寸。

注意:我对 unity 很陌生,现在修修补补了几天,所以我可能是一个非常简单的问题,但是在研究了几个小时之后,我还没有发现任何有用的东西。

最佳答案

设置TextMeshProUGUI 的文本后,textBounds 及其size 直到下一帧才会更新。这是由 Unity 的延迟布局重建引起的。在他们的UI Layout Documentation ,内容如下:

The rebuild will not happen immediately, but at the end of the current frame, just before rendering happens. The reason it is not immediate is that this would cause layouts to be potentially rebuild many times during the same frame, which would be bad for performance.

我继续猜测 GamePlay.GetHoverCanvas() 正在维护一个永远不会被销毁的对象,因此,您的代码在所有情况下都有效,第一次运行。

可能有几种方法可以解决此问题,但最简单的方法是调用 Canvas.ForceUpdateCanvases()在设置 text 和读取 textbounds 的大小之间。它不是最快的函数,但应该可以解决问题。

另一种选择是,代替同步函数,启动一个协程,将 text 设置为一帧,产生下一帧,然后读取 textbounds在其第二个执行框架上。 (这可能会导致尺寸突然出现并且看起来不合需要)。

关于c# - 为什么 TextMeshPro 在设置文本后不更新 textBounds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com