动态添加Ugui组件

动态添加Ugui组件  

 

动态添加是指:在场景中有一个canvas,使用代码,动态添加一个没有canvas的prefab,可是这个prefab须要挂载到canvas下,就是canvans下的ugui组件

若是anchors 的min和max 不是 (0.5, 0.5)的时候就会有问题,添加的位置是不对的,

具体什么缘由不是很懂, 与锚点有关系

一下代码就能够避免这种状况

 

1         GameObject obj = Resources.Load<GameObject>("btn_info_test"); // 要动态添加的物体
2         GameObject child = GameObject.Instantiate(obj);               // 实例化GameObject
3         child.transform.parent = tran;                                // 设置父物体
4         //child.GetComponent<RectTransform>().pivot = obj.GetComponent<RectTransform>().pivot;
5         // 设置anchors min的偏移量 ,就是anchors min 到 控件左下角的偏移量
6         child.GetComponent<RectTransform>().offsetMin = obj.GetComponent<RectTransform>().offsetMin;
7         // 设置anchors min的偏移量 , 就是anchors max 到 控件右上角的偏移量
8         child.GetComponent<RectTransform>().offsetMax = obj.GetComponent<RectTransform>().offsetMax; 
相关文章
相关标签/搜索