0
\$\begingroup\$

I have a canvas with buttons, with a script attached to each button. This script creates an array for buttons and resizes every button to the same size as the longest one in that array (the button with the longest line of text in it). Everything works, but I was wondering: is there is an easier, more automatic way for this instead of having to drag every button in every array in the Inspector tab?

Any ideas would be greatly appreciated

UnityPackage: https://transfer.sh/6BCDG/buttonwidth.unitypackage

public Image[] otherbutton;

void Start () {

    for(int i = 0; i < otherbutton.Length; i++)
    {

        if (otherbutton[i].rectTransform.sizeDelta.x > gameObject.GetComponent<Image>().rectTransform.sizeDelta.x) 
        {
            gameObject.GetComponent<ContentSizeFitter> ().enabled = false;

            gameObject.GetComponent<Image>().rectTransform.sizeDelta = new Vector2( otherbutton[i].rectTransform.sizeDelta.x, otherbutton[i].rectTransform.sizeDelta.y);

        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

Using a layout group would be ideal, but if for some reason that doesn't work with what you're doing you can populate your button array by simply creating a public variable that you place the parent of the buttons in, using the inspector, and then getting the children on start. The code would look something like this:

public Transform parentOfButtons;

private Image[] otherbutton;

void Start()
{
    otherbutton = new Image[parentOfButtons.childCount];
    for (int i = 0; i < parentOfButtons.childCount; i++)
    {
        otherbutton[i] = parentOfButtons.GetChild(i).GetComponent<Image>();
        if (otherbutton[i].rectTransform.sizeDelta.x > gameObject.GetComponent<Image>().rectTransform.sizeDelta.x)
        {
            gameObject.GetComponent<ContentSizeFitter>().enabled = false;

            gameObject.GetComponent<Image>().rectTransform.sizeDelta = new Vector2(otherbutton[i].rectTransform.sizeDelta.x, otherbutton[i].rectTransform.sizeDelta.y);

        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

Maybe more a long comment than an answer

I would improve your code by first creating all the buttons, then search for the maxWidth, store it, and resize all the buttons accordingly.

It seems to me than now you are resizing your buttons too many times, for example if you have 4 buttons, sizing {100px, 120px, 140px, 80px}, when you create the 4th button now you are resizing it 3 times.

\$\endgroup\$
0
\$\begingroup\$

Are the buttons supposed to appear right below each other?

Then put your buttons into a Vertical Layout Group and switch on "Child Force Expand". They will then be automatically enlarged to fit the layout group. No scripting required.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.