Support > NGUI 3 Support

Never use Instantiate(). Use gameObject.AddChild.

(1/2) > >>

ArenMook:
I have to repeat myself every single day here. Never use Object.Instantiate() when working with NGUI. Use gameObject.AddChild instead. Why? Because AddChild does this:

1. Sets the game object's layer (VERY IMPORTANT!)
2. Sets the game object's parent (also very important!)
3. Resets the position/scale
4. Works with Undo functionality

If you use Instantiate, then you are shooting yourself in the foot by creating your UI element in the middle of nowhere, orphaned without a parent. Think of the children! Save a life by using AddChild instead.

JumpCore:

--- Quote ---Think of the children! Save a life by using AddChild instead.
--- End quote ---

Hah! lol

Bradamante3D:
Well, there are reasons why people use Instantiate() over AddChild().

Just like other NGUI users, I have a UIGrid that gets populated dynamically. In Editor mode, I simply don't know how many children the UIGrid will have. So, I need to populate the UIGrid via:

foreach ( string shipName in tradedShips ) {         GameObject b = (GameObject)Instantiate ( buttonGenericGo, Vector3.zero, Quaternion.identity );        b.transform.parent = transform;        b.transform.localScale = Vector3.one;        NGUITools.SetActive ( b, true );        } 
and then call Reposition(). In earlier versions of NGUI that did not work. As a fix, I used a Scrollview-as-second-camera setup in the past. But then, a changing number of UIGrid children would leave the UIGrid or scrollable content in the wrong position. Somewhere in the 3.6.x range of upgrades you introduced fixes for that (wasn't it related to the Start function?). Right now I am using NGUI v3.6.9 and I am somewhat hesitant to upgrade, since now it works.

Here you have explicitely stated why AddChild can not be used in the case of UIGrid. Is the official policy changing?

ArenMook:
I started that AddChild cannot be used with UIGrid? Where? It's just fine. If your example replaces Instantiate with AddChild(gameObject, buttonGenericGo), then it will work as expected.

Bradamante3D:
Hm you probably overlooked the link, *here* is it again.

Navigation

[0] Message Index

[#] Next page

Go to full version