using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class UpdateUIPositionFromPSD : EditorWindow { public static UpdateUIPositionFromPSD window = null; [UnityEditor.MenuItem("程序/PSD To UGUI 辅助工具")] static void Init() { window = GetWindow(typeof(UpdateUIPositionFromPSD), false, "PSD To UGUI 辅助工具") as UpdateUIPositionFromPSD; window.Show(); window.autoRepaintOnSceneChange = true; } GameObject target; Vector2 m_Position; Vector2 m_Size; private void OnGUI() { target = (GameObject)EditorGUILayout.ObjectField("目标", UnityEditor.Selection.activeGameObject, typeof(GameObject), true); m_Position = EditorGUILayout.Vector2Field("坐标", m_Position); m_Size = EditorGUILayout.Vector2Field("大小", m_Size); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("应用")) { RecordChildrenPositions(); Apply(); RestoreChildrenPositions(); } } Vector2 anchorMaxBuf = Vector2.zero; Vector2 anchorMinBuf = Vector2.zero; private void Apply() { if (target == null) { return; } var selected = target.GetComponent(); if (selected == null) { return; } selected.sizeDelta = m_Size; anchorMaxBuf = selected.anchorMax; anchorMinBuf = selected.anchorMin; selected.anchorMax = new Vector2(0, 1f); selected.anchorMin = new Vector2(0, 1f); var newX = m_Position.x * 0.01f - 6.67f + m_Size.x * 0.01f * selected.pivot.x; var newY = 3.75f - m_Position.y * 0.01f - (m_Size.y * 0.01f * (1f - selected.pivot.y)); selected.position = new Vector3(newX, newY, 0f); var position1 = selected.position; selected.anchorMax = anchorMaxBuf; selected.anchorMin = anchorMinBuf; selected.position = position1; } Dictionary childrenPosition = new Dictionary(); private void RecordChildrenPositions() { if (target == null) { return; } childrenPosition.Clear(); int childCount = target.transform.childCount; for (int i = 0; i < childCount; i++) { var child = target.transform.GetChild(i); childrenPosition[child] = child.position; } } private void RestoreChildrenPositions() { foreach (var child in childrenPosition.Keys) { child.position = childrenPosition[child]; } } }