動態添加Ugui組件
阿新 • • 發佈:2017-09-12
instant 場景 ttr orm 需要 res 就會 ugui clas
動態添加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;
動態添加Ugui組件