unity, 動態創建節點時一定要先指定父節點再設置transform

如下,設置transform的代碼必須放在node.transform.parent=transform之後。否則設置將不生效。

     GameObject node = new GameObject ();
node.name=”myNode”;
node.transform.parent = transform;
node.transform.localScale = new Vector3 (1, 1, 1);
node.transform.localPosition = new Vector3 (0, 0, 0);
node.transform.localRotation = Quaternion.identity;

更新(2015-8-7):

細看了一下,控制檯有個warning:

Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.

所以,應該寫成下面這樣纔是標準的:

     GameObject node = new GameObject ();
node.name=”myNode”;
node.transform.SetParent(transform,false);
node.transform.localScale = new Vector3 (1, 1, 1);
node.transform.localPosition = new Vector3 (0, 0, 0);
node.transform.localRotation = Quaternion.identity;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章