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),然后隨便點擊一個組件的錨點,用鼠標拖動一下,再用上面的錨點工具應用錨點,最后勾上自動保存,在切換一下預設物回來,發現錨點應用成功
比手動拖要快多了
如果喜歡,請點個贊吧,感謝