Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A script that makes anchor min max positioned at Gameobject ui corners?

I am a beginner in unity3d and i am struggling to make the Ui anchor min max same position as the Button position when moved, my goal is try to achieve like the pictures below.

enter image description here

enter image description here

as you can see when the button moves the anchors min max does not following with it, in what way should i solve this using C#? at the moment i move my button with the follow script:

    public GameObject SaleButtonPrefab;

    //To loop all the list
    for(int i = 0; i < playerList.Count; i++)
    {

        //Instantiate the button prefab and make a parent
        GameObject nu = Instantiate(SaleButtonPrefab) as GameObject;
        nu.transform.SetParent(ParentButton.transform, false);

        //To set the position
        nu.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, (i*-301) - 0);

    }

Thanks in advance!

like image 884
OddTuna Avatar asked Sep 13 '25 00:09

OddTuna


1 Answers

I have figured it out, and to accomplish my goal i modify some of the scripts i have found useful in the internet. This is the code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GUITest : MonoBehaviour 
{

    private RectTransform t;
    private RectTransform pt;

    void Start()
    {
        t = gameObject.GetComponent<RectTransform>();
        pt = gameObject.GetComponent<RectTransform>().parent as RectTransform;

        if(t == null || pt == null) return;

        Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width,
                                         t.anchorMin.y + t.offsetMin.y / pt.rect.height);
        Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width,
                                         t.anchorMax.y + t.offsetMax.y / pt.rect.height);

        t.anchorMin = newAnchorsMin;
        t.anchorMax = newAnchorsMax;
        t.offsetMin = t.offsetMax = new Vector2(0, 0);
    }
}

To make this work i save this script as C#, after that i attach it to any UI object and when you run your unity game the UI anchor will automatically resize itself around the UI object. i find this useful when instantiating a prefab and looping it because you cant really change the anchors.

Source: http://answers.unity3d.com/questions/782478/unity-46-beta-anchor-snap-to-button-new-ui-system.html

like image 196
OddTuna Avatar answered Sep 15 '25 13:09

OddTuna