static RectTransform PopulateLayout(RectTransform container, LayoutDirection dir, int count) { bool vertical = dir == LayoutDirection.Vertical; if (vertical) { container.gameObject.AddComponent <VerticalLayoutGroup>().SetChildControl(); } else { container.gameObject.AddComponent <HorizontalLayoutGroup>().SetChildControl(); } List <GameObject> cretedObjects = new List <GameObject>(); for (int i = 0; i < count; i++) { RectTransform child = container.AddChild(); Undo.RegisterCreatedObjectUndo(child, "layoutt"); cretedObjects.Add(child.gameObject); child.anchorMin = new Vector2(0, 0); child.anchorMax = new Vector2(1, 1); child.offsetMin = new Vector2(0, 0); child.offsetMax = new Vector2(0, 0); Image im = child.gameObject.AddComponent <Image>(); im.color = im.color.Random(); child.name = "Item " + (i + 1); LayoutElement le = child.gameObject.AddComponent <LayoutElement>(); le.flexibleHeight = (vertical ? 1f / count : 1); le.flexibleWidth = (vertical ? 1 : 1f / count); child.localScale = Vector3.one; //why do we need this } container.name = (vertical ? "VerticalLayout" : "HorizontalLayout"); return(container); }
static void CreateLayout(RectTransform container, bool vertical) { int count = 3; // int spacing = 5; if (vertical) { container.gameObject.AddComponent <VerticalLayoutGroup>().SetChildControl(); } else { container.gameObject.AddComponent <HorizontalLayoutGroup>().SetChildControl(); } // container.gameObject.AddOrGetComponent<LayoutGroupHelper>(); List <GameObject> cretedObjects = new List <GameObject>(); for (int i = 0; i < count; i++) { RectTransform child = container.AddChild(); cretedObjects.Add(child.gameObject); child.anchorMin = new Vector2(0, 0); child.anchorMax = new Vector2(1, 1); child.offsetMin = new Vector2(0, 0); child.offsetMax = new Vector2(0, 0); Image im = child.gameObject.AddComponent <Image>(); im.color = im.color.Random(); child.name = "Item " + (i + 1); LayoutElement le = child.gameObject.AddComponent <LayoutElement>(); le.flexibleHeight = (vertical ? 1f / count : 1); le.flexibleWidth = (vertical ? 1 : 1f / count); } container.name = (vertical ? "VerticalLayout" : "HorizontalLayout"); }
public static RectTransform AddChildRectTransform(this GameObject parent) { RectTransform parentRect = parent.GetComponent <RectTransform>(); return(parentRect.AddChild()); }