gpt4 book ai didi

c# - 如何在 Unity 的 GridLayoutGroup 中获取 child 的世界位置?

转载 作者:行者123 更新时间:2023-11-30 17:31:41 24 4
gpt4 key购买 nike

我有一个 ScrollView ,在它的内容对象中有一个 GridLayoutGroup 组件(内容对象有自己的位置和比例,而不是 (0,0,0) 或 (1,1,1) ),在它下面'几个图像。在运行时,我想取出一个图像并将其父级设置为其他 UI 对象,但我希望图像保持其在屏幕上的位置。

但是我尝试了以下所有方法,都以错误的屏幕位置结束(图像有时甚至移动到屏幕外)。

1 在图像对象上使用 SetParent 方法(尝试将 True 或 false 作为第二个参数):

imageObject.transform.SetParent(otherObj, True);

2 用第一种方式使用SetParent方法,然后手动给图片一个位置,但是id没有出现在鼠标位置(这段代码对于其他不在layoutgroup中的对象也能正常工作):

imageObject.transform.SetParent(otherObj, True);
var p = Camera.main.ScreenToWorldPoint(Input.mousePosition);
imageObject.transform.position = new Vector3(p.x, p.y, 0);

3 调用SetParent后将position设置为原来的值。

var p = imageObject.transform.position;
imageObject.transform.SetParent(otherObj, True);
imageObject.transform.position = new Vector3(p.x, p.y, 0);

4 不使用任何代码,但在运行时在编辑器中,手动将图像拖出到目标父对象。它的位置仍然改变了。

5 不使用任何代码,但在编辑器运行期间,手动取消选中 GridLayoutGroup 以禁用它。图像位置仍然发生变化。

为什么第三种方法不起作用?我认为可能未使用图像对象的 transform.position,因此未使用该值,因此该值不在屏幕上的位置,或者在帧末尾发生了某些事情,因此我重置位置是无用的。

更多信息:我的 Canvas 渲染模式设置为“屏幕空间-相机”。但即使将其更改为叠加,它仍然是相同的结果。 Canvas scaler 模式为“Scale with Screen Size”,屏幕匹配模式为“Expand”。

那么我应该怎么做才能从 GridLayoutGroup 中取出图像,但让它留在屏幕上的位置?谢谢!

最佳答案

经过多次测试,我发现你调用SetParent(objParent, True);后的位置是对的;但由于与 GridLayoutGroup 相关的原因,位置在这之后和帧结束之前的时间发生了变化。因此,记录下该位置并在其他帧中执行您需要的任何操作。

例子:

在主线程中:

 imageObject.transform.SetParent(otherObj, True);
originalPosition = imageObject.transform.position;
imageObject.SetObjectActive(false); // If not do this, the image might flicker at it's position before put it into the GridLayoutGroup. My guess is that it gets rendered before the AdjustTransInTheEndOfFrame method is executed.
StartCoroutine(AdjustTransInTheEndOfFrame(imageObject));

private IEnumerator AdjustTransInTheEndOfFrame(GameObject obj)
{
yield return new WaitForEndOfFrame();
obj.transform.position = originalPosition;
obj.SetObjectActive(true);
}

关于c# - 如何在 Unity 的 GridLayoutGroup 中获取 child 的世界位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47571288/

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