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");

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.

enter image description here


1 Answer 1


Unsure if this is a bug, but setting the anchors has to be done with

rt.anchorMin = new Vector2(0.5f, 0);

and NOT

rt.anchorMin.Set(0.5f, 0);

IMO this is a bug, but will leave it up to others to inform me otherwise.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .