Home > Mobile >  A Unity prefab instance attached to the scene is receiving unwanted scaling
A Unity prefab instance attached to the scene is receiving unwanted scaling

Time:06-25

I'm managing a dynamic UI based on canvas. The UI is created with Layout groups (vertical and horizontal).

One of the dynamic components of this UI is a prefab that I'm instantiating, filling with the needed information, and attaching to the parent that will dynamically place it through a vertical layout.

I can't understand why this instance is attached and rescaled to "0.683". To make it work correctly I have to scale it back to 1 from code. This behaviour since pretty strange... I'm wondering if you have suggestions to avoid the need to resize the object from code. Even if it is not such a problem I rather keep this flow clean.

Note: If I attach the same object manually from the editor, the behaviour is correct and the item is keeping a scale of 1.

CodePudding user response:

If you Instantiate prefab the newly created instance will have the same scale as prefab, but if you change parent of that object to object that is scalled your instantiated prefab will change localScale to keep the same size. If you are talking about UI you probably have "CanvasScaller" component on the Root object in your hierarchy that provides scalling for UI. So basicaly

  1. CanvasScaller sets scale to (1.45, 1.45, 1.45)
  2. You instantiate object without parent and it has scale (1, 1, 1)
  3. You change parent of object to be a Child of CanvasScaller
  4. The scale gets recalculated and your objects scale is (0.68, 0.68, 0.68) to maintain the same size

You should probably use one of the Instantiate overrides that takes Transform parent as one of the arguments so you don't need to change it later.

  • Related