When adding prefab button to canvas with code, scale is wrong.

I have a canvas in my scene, and a button prefab. If I drag the button to the canvas in edit or play mode, everything looks ok, but when I add it with code, the scale gets weird. X, Y and Z of the buttons rect transform is set to 0.4169381. If I set it to 1 manually, it looks correct.

The prefab has 1 in the scale, apparently, since when dragging it in play mode, after it has generated my buttons, it also looks correct.

I use this code which is run on Awake of the canvas object. It’s looped through a list of buttons to create:

GameObject newButton = Instantiate(mButtonPrefab);
newButton.transform.SetParent(transform);

I tried different options in Canvas Scaler, but this changes all buttons, so the small buttons get smaller.

Any ideas?

Solved it by setting the second argument to false,

newButton.transform.SetParent(transform,false);

From the docs of setParent:
worldPositionStays If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

6 Likes