Tokyo, Japan |


Move an NGUI component to the position of a gameobject

It’s often necessary to place a NGUI component in the exact position as a 3D gameobject. By just using transform.position without doing some calculations beforehand, you’ll get unpredictable results and the NGUI object will end up in a wrong place. That’s because NGUI uses its own coordinates and the gameobject uses world space coordinates, so the position won’t match.

So, how can you solve this?

Let’s say you have these items in the scene:

– object1 (gameobject)
– object2 (NGUI object)
– camera1 (3D camera)
– camera2 (NGUI’s UICamera)

First, get screen position of the gameobject using WorldToScreenPoint:

Vector3 screenPos = camera1.WorldToScreenPoint(object1.transform.position);

Next, take the value of screenPos and position the NGUI element using ScreenToWorldPoint like so:

object2.transform.position = camera2.ScreenToWorldPoint(screenPos);

Now you will see the NGUI element match the position of the gameobject.

Note: All code in this article is written in C#.