c# - 在 Content Size Fitter 更新内容的 Rect Transform 后,如何让 Unity Scroll Rect 滚动到底部?

标签 c# unity3d layout scroll scrollbar

我有一个要动态添加内容的垂直 ScrollView 。为此,我将一个 Content Size Fitter 组件和一个 Vertical Layout Group 组件附加到 Content 游戏对象,这样每当我将新游戏对象实例化为它的子对象时,它的 Rect Transform 就会自动增长。如果滚动条已经在底部,我想在底部添加新对象后,让滚动条保持在底部。所以我这样做:

    if ( scrollRect.verticalNormalizedPosition == 0 )
    {
        isAtBottom = true ;
    }

    ScrollViewItem item = Instantiate( scrollViewItem, scrollRect.content ) ;

    if ( isAtBottom )
    {
        scrollRect.verticalNormalizedPosition = 0 ;
    }

但是,这不起作用,因为在我将 verticalNormalizedPosition 设置为零时,新实例化的 ScrollView 项尚未增加 Rect Transform 的大小。因此,当 Rect Transform 最终更新时,滚动到底部为时已晚。

为了说明,假设我的内容有 400 像素高,滚动条一直在底部。现在我向其中添加一个 100 像素高的对象。然后我将滚动条发送到底部,但它仍然认为内容是 400 像素高。然后内容大小更新为 500 像素,但滚动条向下移动了 400 像素,因此它只向下移动了 80% 而不是 100%。

有两种可能的方法来解决这个问题。我想要一种强制 Content Size Fitter 立即更新的方法,或者一种将 Content Size Fitter 更新作为事件响应的方法。

通过研究和实验,我几乎成功地通过将这些行按以下顺序放置在第一个选项中:

Canvas.ForceUpdateCanvases();
scrollRect.content.GetComponent<VerticalLayoutGroup>().CalculateLayoutInputVertical() ;
scrollRect.content.GetComponent<ContentSizeFitter>().SetLayoutVertical() ;
scrollRect.verticalNormalizedPosition = 0 ;

但是,它并没有完全滚动到底部。它总是大约 20 像素远。所以我想知道是否还有一些我不会强制发生的布局操作。也许是填充或其他东西。

最佳答案

好的,我相信我已经弄明白了。在大多数情况下,Canvas.ForceUpdateCanvases(); 是您在将 verticalNormalizedPosition 设置为零之前需要做的所有事情。但就我而言,我添加到内容中的项目本身也有一个垂直布局组组件和一个内容大小调整器组件。所以我必须按以下顺序执行这些步骤:

Canvas.ForceUpdateCanvases();

item.GetComponent<VerticalLayoutGroup>().CalculateLayoutInputVertical() ;
item.GetComponent<ContentSizeFitter>().SetLayoutVertical() ;

scrollRect.content.GetComponent<VerticalLayoutGroup>().CalculateLayoutInputVertical() ;
scrollRect.content.GetComponent<ContentSizeFitter>().SetLayoutVertical() ;

scrollRect.verticalNormalizedPosition = 0 ;

遗憾的是,关于这些方法的文档太少了。

关于c# - 在 Content Size Fitter 更新内容的 Rect Transform 后,如何让 Unity Scroll Rect 滚动到底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613015/

相关文章:

c# - Windows 8 - WriteTextAsync 异常 "Cannot evaluate expression because a native frame is on top of the call stack."

extjs - ExtJS 中适合布局的多个项目

java - 以DecoratorPanel内部的GWT DockLayoutPanel + ScrollPanel为中心

c# - 使用 EWS 和 C# 获取附件失败并出现 ServiceMethodException

c# - 执行 Web 数据提取

C# Parallel.For 意想不到的结果

gridview 中的 Android (Xamarin) 填充

javascript - 获取客户的一些身份信息

ios - 如何设计 ARKit 使用的 Animoji 3D 模型?

c# - Ubuntu 19.10 上的 Unity3D,带有 vscode 和 C# 扩展 : get an error and the autocomplete doesn't working