uGui alignment is wrong when adding prefabs to canvas

This is for the new uGui in 4.6.

I have some gui elements laid out into panels that I’ve made into prefabs. I’d like to programmatically add them to the canvas when they are needed. When I drag and drop them onto the canvas in the editor they show up perfectly, but when I do what I assume is the exact same thing in code the alignment is all off:

canvas = GameObject.Find("Canvas");

guiMainPanel = (GameObject)Instantiate (Resources.Load<GameObject>("Gui/MainPanel"));
guiMainPanel.transform.SetParent (canvas.transform);

In one case, I noticed that the “Right” value of the in-game clone was different from the value of the prefab when I add it manually. I fixed it by adding the following code:

RectTransform rt = guiMainPanel.GetComponent<RectTransform>();
rt.offsetMax = new Vector2(0, rt.offsetMax.y);

Besides being an ugly hack, it only works for prefabs with a certain type of alignment (Horizontally stretched), not on all my prefabs.

Is this a bug in uGui, or am I doing something wrong?

I was running into similar issues; maybe this will help you. It seems that you can pass a second argument to transform.SetParent, like so:

guiMainPanel.transform.SetParent(canvas.transform, false);

Doing this should, in addition to setting the parent, cause the object to position itself correctly in the local space of the canvas. Without the false flag, it will keep it’s original world position when it sets the parent.