c# - 实例化后的Unity3D C#面板定位

标签 c# unity3d transform panel rect

我正在实例化一个 GO,它有一个面板组件 (RectTransform) 作为场景中存在的 Canvas 的子组件:

_heroSelectUI = (GameObject)Instantiate (_heroSelectUIPrefab, GameObject.Find ("Canvas").GetComponent<Transform>());

创建后,它会获得以下值:

Panel Values

“Left”、“Top”、“Right”和“Bottom”得到一些不需要的值(可能是因为现有的 Canvas 似乎具有相同的值)。

面板prefabs值为0,如何在实例化后将它们设置回0?我找不到适合 RectTransform 的变量。

最佳答案

根据documentation

For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right anchor.

尝试做如下:

RectTransform rt = _heroSelectUI.GetComponent<RectTransform>();
rt.offsetMin = rt.offsetMax = Vector2.zero ;

否则,根据文档,您也可以在设置父级时尝试这样做:

Prefabs of UI elements are instantiated as normal using the Instantiate method. When setting the parent of the instantiated UI element, it’s recommended to do it using the Transform.SetParent method with the worldPositionStays parameter set to false.

_heroSelectUI = (GameObject)Instantiate (_heroSelectUIPrefab, GameObject.Find ("Canvas").GetComponent<RectTransform>(), false);

或:

_heroSelectUI = (GameObject)Instantiate (_heroSelectUIPrefab );
_heroSelectUI.GetComponent<Transform>().SetParent( GameObject.Find ("Canvas").GetComponent<RectTransform>(), false ) ;

关于c# - 实例化后的Unity3D C#面板定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230421/

相关文章:

c# - 如何将 Expression<Func<T, DateTime>> 转换为 Expression<Func<T, object>>

android - onStop() 中的 finish() 之后的 onCreate()

javascript - jQuery 转换不起作用

xcode - 如何计算矩形到四边形的 3D 变换矩阵

jquery - 使用 css 或 jquery 创建倾斜 45 度并与底部对齐的列表

c# - 在 ASP .NET 中通过 C# 获取存储过程脚本

c# - 带有选项卡项的用户控件不显示

c# - 如何使用Nest将具有数组值的settings属性添加到ES-index

unity3d - Unity3D 中的垂直同步计数是多少?

c# - 胶囊对撞机不统一跳跃