Relative newbie to Unity so please excuse any oversights. I have a component (canvas/panel) that I'm wanting to add a panel to, so that when the parent component's height changes, the child panel's height changes to match. I've achieved this manually using the inspector (see top half of attached pic) to set the anchor points at min(0.5, 0) and max(0.5, 1) (pivot is unchanged at (0.5,0.5)).
I want to create that stretching panel in scripting, and have the following code that results in the bottom half of the attached pic where the rect transform's anchors aren't set at all.
GameObject panel2 = GameObject.Find("Panel2"); GameObject divider = new GameObject("RunTimeLine"); divider.layer = LayerMask.NameToLayer("UI"); divider.transform.SetParent(panel2.transform); CanvasRenderer c = divider.AddComponent<CanvasRenderer>(); RectTransform rt = (RectTransform)divider.AddComponent<RectTransform>(); Image img = divider.AddComponent<Image>(); img.color = Color.red; rt.localPosition = new Vector2(0f, 0f); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 20); rt.anchorMin.Set(0.5f, 0); rt.anchorMax.Set(0.5f, 1);
Any suggestions? I've also tried setting the min/max offsets and pivot but haven't been able to create what I've got manually in the inspector.