Dynamically resize UI.Panel through code


I have a panel that I am dynamically adding objects to (prefabs I’ve created) at runtime to represent files. The prefabs are added one after the other horizontally. I keep track of the X position when adding a new object and increment. This works fine but the objects within the panel now exceed the width of the panel.

I’ve set the panel up so its a drag panel. You can scroll through the horizontal list. But the scroll is only as wide as the panel, in otherwords, the rest of the objects are off the screen and cannot be dragged to.

I need to dynamically resize the panel as I add the new object. I have two questions:

  1. How do I ascertain the current size of the panel container?

  2. How do I then resize the panel at runtime?

Thanks in advance!!

Any ideas where I am going wrong?

Using Debug.Log("panel width = " +
panelRectTransform.sizeDelta.x); I can
see the correct width of the panel but
it never gets updated.

This worked for me:
instead of panelRectTransform.sizeDelta.Set((float)xPos + 10, panelRectTransform.sizeDelta.y);
panelRectTransform.sizeDelta = new Vector2((float)xPos + 10, panelRectTransform.sizeDelta.y);

I believe you want the “sizeDelta” property of the panel’s RectTransform. You can both get and set it.

You could also look at the “Content Fitter” component if you want Unity to handle it automatically.

I’m not completely across the new UI layout stuff in Unity 4.6. But I believe that you may be able to handle this automatically (depending on exactly what your requirements are), e.g. add a Layout|Horizontal Layout Group to the panel and add a Layout Element to each of the prefabs to be added to the panel.

Good video tutorial here.

In short, the new unity UI provides the kind of vbox, hbox, gridbox UI builders/resizers you see in other GUI toolkits. They are, however, currently not very well documented, as far as I can see.