1.编辑器脚本需要放到Editor文件夹下面
简单操作,快速让锚点分布在组件四个顶点
选中组件(可以单选,可以多选) 点击Tools/自适应锚点
代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class AnchorController { [MenuItem("Tools/自适应锚点")] private static void SelectionAnchor() { GameObject[] objs = Selection.gameObjects; for (int i = 0; i < objs.Length; i++) { if (objs[i].GetComponent<RectTransform>() == null) continue; AnchorCon(objs[i]); } } private static void AnchorCon(GameObject obj) { //位置信息 Vector3 partentPos = obj.transform.parent.position; Vector3 localPos = obj.transform.position; //------获取rectTransform---- RectTransform partentRect = obj.transform.parent.GetComponent<RectTransform>(); RectTransform localRect = obj.GetComponent<RectTransform>(); float partentWidth = partentRect.rect.width; float partentHeight = partentRect.rect.height; float localWidth = localRect.rect.width * 0.5f; float localHeight = localRect.rect.height * 0.5f; //---------位移差------ float offX = localPos.x - partentPos.x; float offY = localPos.y - partentPos.y; float rateW = offX / partentWidth; float rateH = offY / partentHeight; localRect.anchorMax = localRect.anchorMin = new Vector2(0.5f + rateW, 0.5f + rateH); localRect.anchoredPosition = Vector2.zero; partentHeight = partentHeight * 0.5f; partentWidth = partentWidth * 0.5f; float rateX = (localWidth / partentWidth) * 0.5f; float rateY = (localHeight / partentHeight) * 0.5f; localRect.anchorMax = new Vector2(localRect.anchorMax.x + rateX, localRect.anchorMax.y + rateY); localRect.anchorMin = new Vector2(localRect.anchorMin.x - rateX, localRect.anchorMin.y - rateY); localRect.offsetMax = localRect.offsetMin = Vector2.zero; } }
踩的坑:(纳闷的一笔)
在预设物里面,用上面工具自适应之后保存,换一个预设物,在重新进刚刚的预设物里面,发现刚刚预设物的锚点跟没应用之前是一样的
最后解决办法
先取消自动保存(AutoSave),然后随便点击一个组件的锚点,用鼠标拖动一下,再用上面的锚点工具应用锚点,最后勾上自动保存,在切换一下预设物回来,发现锚点应用成功
比手动拖要快多了
如果喜欢,请点个赞吧,感谢