- Home /
Get height and width of gameobject set with anchors
I am trying to change the height of a parent GameObject to match the combined heights of the children.
I have 2 objects in another object. I have the sizes set by anchors.
Rect Transforms are all 0, not that that matters.
Object 1 min Y = .9
max Y = 1
Object 2 min Y = 0
max Y = .9
If I could scale the outside object to fit the size of the children, that would be idle.
Layout group and content size fitter does not work for this situation because the preferred size has to be in units, not percentages.
I thought I could get the height of the objects and adjust the height myself, but that does not work either. I've tried the following and the height is always 0:
GameObject title = GameObject.Find("Title");
GameObject body= GameObject.Find("Body");
titleRect = RectTransformUtility.PixelAdjustRect(title.GetComponent<RectTransform>(), title.GetComponent<Canvas>());
bodyRect = RectTransformUtility.PixelAdjustRect(body.GetComponent<RectTransform>(), body.GetComponent<Canvas>());
float titleY; titleY = title.GetComponent<RectTransform>().rect.height;
titleY = title.GetComponent<RectTransform>().sizeDelta.y;
Vector3[] arr = new Vector3[4]; .
title.GetComponent<RectTransform>().GetLocalCorners(arr);
titleY = arr[2].y - arr[0].y;
//titleY = title.GetComponent<Collider2D>().bounds.size.y; //error no Collider attached
//titleY = title.GetComponent<Renderer>().bounds.size.y; //error no Render
//titleY = title.GetComponent<Mesh>().bounds.size.y; //error no Mesh
You would think Unity would have a simple parent to fit children, but I guess using anchors to size things by percent makes things more complicated.
Your answer
Follow this Question
Related Questions
UI 4.6: custom anchors breaking sizeDelta 0 Answers
How to change the Width and Height in the script C#? (New Gui Unity 4.6 beta) 2 Answers
Setting a button size via script 1 Answer
Prefab Instance changing when loading scene in editor 0 Answers
Get Rect in Screen Space from RectTransform (Screen Space - Camera) 1 Answer