实例化后的Unity3D C#面板定位
Unity3D C# positioning of panel after instantiation
我正在实例化一个 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 ) ;
我正在实例化一个 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 ) ;