using UnityEditor;
using UnityEngine;
namespace MedjeDev
{
public class AnchorsToCorners
{
[MenuItem("GameObject/Anchors To Corners", false, 0)]
static void SetAnchorsToCorners()
{
// Get the currently selected GameObject in the editor
GameObject selectedObject = Selection.activeGameObject;
if (selectedObject != null)
{
RectTransform rt = selectedObject.GetComponent();
if (rt != null)
{
if (rt.parent != null)
{
// Record the RectTransform itself for undo purposes
Undo.RecordObject(rt, "Set Anchors To Corners");
RectTransform rtp = rt.parent.GetComponent();
if (rt == null || rtp == null)
return;
Vector2 newAnchorsMin = new Vector2(rt.anchorMin.x + rt.offsetMin.x / rtp.rect.width,
rt.anchorMin.y + rt.offsetMin.y / rtp.rect.height);
Vector2 newAnchorsMax = new Vector2(rt.anchorMax.x + rt.offsetMax.x / rtp.rect.width,
rt.anchorMax.y + rt.offsetMax.y / rtp.rect.height);
rt.anchorMin = newAnchorsMin;
rt.anchorMax = newAnchorsMax;
rt.offsetMin = rt.offsetMax = new Vector2(0, 0);
// Mark the RectTransform as dirty to notify Unity of the change
EditorUtility.SetDirty(rt);
}
}
else
{
Debug.LogWarning("Selected GameObject does not have a RectTransform component.");
}
}
else
{
Debug.LogWarning("No GameObject selected to adjust.");
}
}
}
}