Author Topic: Positioning issues with NGUI Sprites on instantiated prefabs.  (Read 4467 times)

CoderBear

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 34
    • View Profile
Hi I am trying to spawn an NGUI sprite (not a NGUI Unity2D sprite) only when needed.  It for some reason normally spawns at (0,0,0) despite the prefabs set position.  So I set it in code and then gets a really weird position  as shown below in the picture.  Here is the code used:
  1. NGUITools.AddChild (panel.gameObject, mobFollower); // Spawn and add to panel so it shows up in the scene on top
  2. spawnedMobs.Add (GameObject.FindWithTag ("follower"));  // Add to list of spawned enemies for the current combat.
  3. Debug.Log ("Vector3 position of pfFollower (clone) was " + GameObject.FindWithTag ("follower").transform.position);
  4. GameObject.FindWithTag ("follower").transform.Translate (MOB1_POS);  // Place newly spawned object at the correct spot on the screen.
  5. Debug.Log ("Vector3 position of pfFollower (clone) is " + GameObject.FindWithTag ("follower").transform.position);
  6.  


As you can see the code console itself says the code worked, but the inspector tells a different story.  If I don't do anything it just spawns at center (0,0,0).

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Positioning issues with NGUI Sprites on instantiated prefabs.
« Reply #1 on: April 07, 2014, 11:15:01 PM »
NGUITools.AddChild resets the position to (0, 0, 0). Look inside that function.

NGUI works in virtual pixels, so you using transform.Translate may not give you the expected results. By default NGUI's UI is scaled to a very small size -- (2 / Screen height) to be exact. If you are trying to place a sprite at screen coordinates, you need to first covert screen coordinates to world coordinates using the Camera, then convert world coordinates to local coordinates using widget.transform.parent.InverseTransformPoint(pos). This will give you the correct local position which you can use to position your widget: widet.transform.localPosition = pos;

CoderBear

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 34
    • View Profile
Re: Positioning issues with NGUI Sprites on instantiated prefabs.
« Reply #2 on: April 08, 2014, 12:26:19 PM »
Thanks yes my fellow programmer was having a similar issue and figured that one out.

but hey it is fixed and working now so woot!