3
\$\begingroup\$

I'm instantiating UI objects with buttons on them into a scrollrect. For some reason, all of the buttons will ignore their bottom half with the exception of the last prefab instantiated. Below is a gif to show the problem. I have it set to turn red when the button is highlighted. When the mouse isn't in a highlight position clicking will do nothing so I know it's not just a highlighting issue.

Buttons seem to be being ignored :(

Here is the code that I'm using to instantiate the scene.

    //Instantiate the parent UI
    MyLoadGUI = (GameObject)Instantiate(LoadGUI);

    //Get the RectTransform of the scroll rect so I can add each level to the right thing.
    RectTransform[] rt = MyLoadGUI.GetComponentsInChildren<RectTransform>();
    RectTransform myRt = new RectTransform();
    for (int i = 0; i < rt.Length; i++)
    {
        if (rt[i].name == "Scroll Panel")
        {
            myRt = rt[i];
            break;
        }

    }
    //We're going to make 6 fake levels
    int levelCount = 6;
    int levelSize = 88; //How tall the levels are

    int height = Mathf.Max(levelSize * levelCount, 252);

    myRt.sizeDelta = new Vector2(myRt.sizeDelta.x, height);
    myRt.anchoredPosition = new Vector2(myRt.anchoredPosition.x, -height);

    for (int i = 0; i < levelCount; i++)
    {
        GameObject lsl = (GameObject)Instantiate(LoadSingleGUI);
        RectTransform rect = lsl.GetComponent<RectTransform>();
        rect.SetParent(myRt, false);
        rect.anchoredPosition = new Vector2(0, -37 - (i * levelSize));

        //Fill in fake details.  Doesn't run anything related to the button.
        lsl.GetComponent<LoadLevelBar>().BuildRandom();
    }

So, nothing that should be affecting the button that I can see. I thought that the button was getting resized, but when checking in the scene the button is stretched all the way across the prefab. Any ideas why the button isn't working properly?

Button is all the way across

\$\endgroup\$
  • \$\begingroup\$ You can try to use a grid layout group or a vertical layout group with some Layout Element on your children gameobject. \$\endgroup\$ – Sata Dec 11 '15 at 8:32
  • \$\begingroup\$ I got the same problem. I just deleted the dysfunctional buttons and duplicated the working one. Kind of annoying. \$\endgroup\$ – user83438 May 13 '16 at 21:21
1
\$\begingroup\$

I have encountered this problem before. Its related to the anchor points. Like Sata suggested you should use a Layout Group when instantiating UI elements like this.

\$\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.