今天碰到一个很奇怪的问题,游戏中很多Button的缩放不是依靠中心点而缩放的,检查了一下,原来是RectTransform的pivot设置有问题,所以写了一个unity扩展工具,方便修改prefab的button
使用方法
选中prefab--------->选择这个扩展方法执行
[MenuItem("GameObject/DMTools/【Button】设置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);
//设置按钮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);
}