今天碰到一個很奇怪的問題玻熙,游戲中很多Button的縮放不是依靠中心點而縮放的仔燕,檢查了一下螟蝙,原來是RectTransform的pivot設(shè)置有問題,所以寫了一個unity擴展工具扼褪,方便修改prefab的button
使用方法
選中prefab--------->選擇這個擴展方法執(zhí)行
[MenuItem("GameObject/DMTools/【Button】設(shè)置Button縮放為中心點縮放", priority = 21)]
public static void SetPrivot()
{
double time = DateTime.Now.TimeOfDay.TotalMilliseconds;
GameObject go = Selection.activeGameObject;
if (null == go) return;
//true代表 遍歷未顯示的游戲物體
Button[] button = go.GetComponentsInChildren<Button>(true);
Debug.Log("button.Length:" + button.Length);
Animator ani;
RectTransform trans;
float pos_x = 0;
float pos_y = 0;
float rect_width = 0;
float rect_height = 0;
foreach (Button btn in button)
{
ani = btn.GetComponent<Animator>();
if (ani == null || ani.runtimeAnimatorController.name != "Button_ScaleAni")
{
continue;
}
trans = btn.GetComponent<RectTransform>();
pos_x = trans.anchoredPosition.x;
rect_width = (float)((0.5 - trans.pivot.x) * trans.rect.width);
pos_y = trans.anchoredPosition.y;
rect_height = (float)((0.5 - trans.pivot.y) * trans.rect.height);
//設(shè)置按鈕position和pivot
trans.anchoredPosition = new Vector2(pos_x + rect_width, pos_y + rect_height);
trans.pivot = new Vector2(0.5f, 0.5f);
Debug.Log("Set GameObject Name: " + trans.gameObject.name);
}
Debug.Log("Set pivot End," + (DateTime.Now.TimeOfDay.TotalMilliseconds - time) / 1000);
}