unity scrollview中如何定位到指定的克隆预制体的位置

我用scrollview做了一个动态生成的列表,我想打开这个列表的时候可以定位到特定的预制体对象,请问该怎么做?
我在网站内搜索的方法都试了,但是都没有反应,不报错,能运行但是也没有效果。

ChatGPT尝试为您解答,仅供参考
要定位到 ScrollView 中的特定对象,您需要获取该对象的位置并将其转换为 ScrollView 的滚动位置。


首先获取该对象的位置,可以使用 RectTransform 组件的 anchoredPosition 属性。 anchoredPosition 属性表示对象相对于其父对象的偏移位置,因此要获取该对象相对于 ScrollView 的位置,您需要获取 ScrollView 的 Content 组件(即包含该对象的父对象),然后将 anchoredPosition 属性值与 Content 的 anchoredPosition 属性值相减。


接下来,将获取的位置转换为 ScrollView 的滚动位置。这可以通过使用 ScrollRect 组件的 NormalizedPosition 属性来实现。 NormalizedPosition 属性表示当前滚动位置的百分比,因此要将获取的位置转换为 NormalizedPosition,您需要获取 ScrollView 的 Content 组件的尺寸,然后将获取的位置除以 Content 的尺寸。

例如,假设您有以下代码:

ScrollView scrollView;
GameObject targetObject;

void ScrollToObject() {
  RectTransform targetTransform = targetObject.GetComponent<RectTransform>();
  RectTransform contentTransform = scrollView.GetComponent<ScrollRect>().content;
  Vector2 targetPosition = targetTransform.anchoredPosition - contentTransform.anchoredPosition;
  Vector2 contentSize = contentTransform.sizeDelta;
  Vector2 normalizedPosition = targetPosition / contentSize;
  scrollView.GetComponent<ScrollRect>().normalizedPosition = normalizedPosition;
}

上述代码将定位到 ScrollView 中的 targetObject 对象。