Установите положение GameObject с помощью предустановок привязки через код в Unity - PullRequest
0 голосов
/ 04 августа 2020

В редакторе Unity можно установить позицию на основе предустановок привязки, например:

enter image description here

My goal is to be able to do this via code. The final result should position some buttons inside a parent panel element (one at top left, top right, center left, center right, bottom left, bottom right).

Now, I have managed to succeed partially by implementing a solution where I set anchorMin and anchorMax on the RectTransform as suggested в этом посте . Например:

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;
            }
    ...

Однако, когда я запускаю код, я получаю что-то вроде этого:

enter image description here

When I use the editor, everything is smooth as I want it to be : enter image description here

I've researched the issue, but could only find a partial solution to the problem in these posts :

Любая идея о том, как правильно решить эту проблему, буду очень признателен. :)

Ответы [ 2 ]

2 голосов
/ 04 августа 2020

Я только что сделал для этого код.

Result.gif

It's just test code. So it made very roughly but I think you can get the point. This code work properly only when 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 вместо этого? проверьте ссылку ниже https://docs.unity3d.com/Packages/com.unity.ugui@1.0 / manual / script-GridLayoutGroup. html

0 голосов
/ 04 августа 2020

Это потому, что ваша точка поворота по умолчанию установлена ​​на Vector2(0.5f, 0.5f) (центр элемента пользовательского интерфейса). Чтобы решить эту проблему, вы можете сделать что-то вроде:

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
    }
    ...
}
...