1

Im new to unity. When I instantiate a new prefab GameObject from inside script as follows:

GameObject newArrow = (GameObject)Instantiate(arrowPrefab);  
newArrow.transform.position = arrowSpawnTransform.position;

But this is creating the object in the root hierarchy(and not inside "UI Root" of NGUI). When I add any object outside of the UI-Root (of NGUI) it adds it to some location far away from the camera, also with a huge dimension. Can someone help me with how to add the newly created prefab under "UI Root" ?

It would be great of someone also lets me know about the positioning and scaling associated with native unity and NGUI. I try hard but am not understanding where to keep what object and in what size so that it comes out as expected. I'll appreciate any help that can be provided. Thanks !

EDIT: I have found a way to place the new prefab inside "UI Root" thru: newArrow.transform.parent = gameObject.transform.parent; after instantiating.

But still the scaling is huge. It's like multiple times bigger than the screen size. Please help me with this. What should I be doing ?

Rune Vejen Petersen
  • 3,201
  • 2
  • 30
  • 46
user1102532
  • 495
  • 6
  • 16

2 Answers2

3

When working with UI elements in NGUI, don't use Instantiate. Use NGUITools.AddChild(parent, prefab).

Dover8
  • 607
  • 3
  • 17
0

NGUI's scale with respect to the rest of the objects in the scene is rather microscopic. If you look at the UIRoot object, you will notice that its scale is measured in thousandths of a meter (default object resolution of 1 typically represents a meter). That is why when you instantiate a prefab and attach it to any object under the UIRoot it appears gigantic relative to the scale of the UIPanel. You could manually scale down the object to the appropriate size, or let NGUI do it for you (as indicated by Dover8) by utilizing NGUITools.AddChild(parent, prefab). In fact, this is the proper way to do so. Don't try to do it manually. The results will be unpredictable and can lead to inappropriate behavior of components. Here's a link to Tasharen's forum on this topic: http://www.tasharen.com/forum/index.php?topic=779.0

Positioning is a bit more complicated. Everything is relative to anchors. Anchor positions are a relationship between a parent object (usually a panel) and a target (usually some form of widget such as a sprite or label). They are controlled by four values relative to the edges of the panel (or parent object), right, left, bottom, and top with respect to the edges of the target (varies by position). Each of these are modified by an integer value (in pixels) that modify the dimensions of the target relative to the parent. There are many examples included with NGUI. I suggest that you look over them. In particular, pay attention to Example 1 - Anchors. I learned a lot from studying these examples, but they don't really cover the full power of NGUI, but they are an excellent starting point.

memBrain
  • 33
  • 7