我正在实例化一个 GO,它有一个面板组件 (RectTransform) 作为场景中存在的 Canvas 的子组件:
_heroSelectUI = (GameObject)Instantiate (_heroSelectUIPrefab, GameObject.Find ("Canvas").GetComponent<Transform>());
创建后,它会获得以下值:
“Left”、“Top”、“Right”和“Bottom”得到一些不需要的值(可能是因为现有的 Canvas 似乎具有相同的值)。
面板prefabs值为0,如何在实例化后将它们设置回0?我找不到适合 RectTransform 的变量。
最佳答案
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/