动态添加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; 

 

posted @ 2017-09-12 17:08  silent-bobo  阅读(348)  评论(0编辑  收藏  举报