通过 Unity 中的代码使用 Anchor Presets 设置 GameObject 的位置

Set GameObject's position with Anchor Presets through Code in Unity

在unity编辑器中,可以根据anchor预设来设置位置,例如:

我的目标是能够通过代码做到这一点。最终结果应将一些按钮放置在父面板元素内(一个位于左上角、右上角、左中角、右中角、左下角、右下角)。

现在,我通过实施一个解决方案取得了部分成功,我按照建议在 RectTransform 上设置了 anchorMinanchorMax in this post。如:

public static void SetAnchor(this RectTransform source, AnchorPresets allign)
    {
        source.anchoredPosition = new Vector3(0, 0, 0);

        switch (allign)
        {
            case (AnchorPresets.TopLeft):
            {
                source.anchorMin = new Vector2(0, 1);
                source.anchorMax = new Vector2(0, 1);
                break;
            }
    ...

然而,当我 运行 代码时,我得到这样的东西:

当我使用编辑器时,一切都如我所愿:

我研究了这个问题,但只能在这些帖子中找到问题的部分解决方案:

任何关于如何正确解决这个问题的想法将不胜感激。 :)

我刚刚为此编写了一些代码。

这只是测试代码。所以它非常粗略,但我认为你能明白这一点。 此代码仅在 AnchorMax == AnchorMin

时才能正常工作
public class TEST : MonoBehaviour
{
    [SerializeField] RectTransform source;
    
    void Update() {    
        Vector2 shiftDirection = new Vector2(0.5f - source.anchorMax.x, 0.5f - source.anchorMax.y);
        source.anchoredPosition = shiftDirection * source.rect.size;    
    }
}

但是,为什么不使用 GridLayout 而不是这个? 检查下面 link https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-GridLayoutGroup.html

这是因为您的枢轴默认设置为 Vector2(0.5f, 0.5f)(UI 元素的中心)。要解决此问题,您可以执行以下操作:

switch (allign)
{
    case (AnchorPresets.TopLeft):
    {
        source.anchorMin = new Vector2(0, 1);
        source.anchorMax = new Vector2(0, 1);
        source.pivot = new Vector2(0, 1);
        break;
    }

    // Just an additional example
    case (AnchorPresets.BottomRight):
    {
        var anchorPoint = new Vector2(1, 0);

        source.anchorMin = anchorPoint;
        source.anchorMax = anchorPoint;
        source.pivot = anchorPoint;
        source.sizeDelta = Vector2.zero; // Not sure if this is needed
    }
    ...
}