Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 4.6: Button instances added at runtime are not scaled by Reference Resolution?

Tags:

unity3d

(Using Unity 4.6.0b20)

I've hit a problem where prefab button size works correctly when added in editor but seems to ignore Reference Resolution when added by script.

This uses a Canvas with Reference Resolution 1280x720 and MatchWidthOrHeight. Canvas has a Panel Vertical Layout Group for the buttons. The Button has Preferred Width/Height, and it is saved as a Prefab so new instances can be created from assets at runtime.

enter image description here

In the editor I can drag the prefab to scene to add instances to the panel which also has width 102 and they stack and scale nicely:

enter image description here

But when instead I add new instances of the prefab via script to the Panel they appear with the wrong size. Looking at the dimensions my guess is the 102 pixel size is not being scaled by the Reference Resolution:

enter image description here

The script code creates the instance via GameObject.Instantiate() and adds to the Panel by setting transform.parent:

GameObject uiInstance = (GameObject)GameObject.Instantiate(Resources.Load<GameObject>(assetPath));
uiInstance.transform.parent = unitButtonsPanel.transform;

I assume either there is more that needs to be done when adding the Button to the Panel than just setting Parent, or it's a bug with the beta...

Suggestions?

like image 348
mwk Avatar asked Oct 03 '14 22:10

mwk


2 Answers

Use the method transform.SetParent passing false in the second parameter:

transform.SetParent(transform, false);

This way you can prevent world positioning and scaling. You can find more information in the unity manual, searching for "UICreateFromScripting".

like image 57
Rod Avatar answered Sep 30 '22 21:09

Rod


I found the cause -- when the prefab is added by script the Scale values are set incorrectly; in this test Scale was being set to 1.186284.

But if the script sets scale to 1.0 immediately after adding the button:

GameObject uiInstance = (GameObject)GameObject.Instantiate(Resources.Load<GameObject>(assetPath));
uiInstance.transform.parent = unitButtonsPanel.transform;
// HACK force scale to 1.0
uiInstance.transform.localScale = Vector3.one;

the new button instances are sized correctly.

imho this is a Unity bug because adding the prefab instance in the editor sets scale 1.0, the prefab itself has scale 1.0, so I can't see a reason why adding it from script should act differently. But I'm kind of guessing as there's not much documentation for the new UI yet :)

like image 31
mwk Avatar answered Sep 30 '22 22:09

mwk