Home/Unity Tidbits

So I had to learn Unity programming not too long ago. I've done ports to Unity in the past but those involved more or less stubbing all the API functions and then coding Unity equivalents for them later. Recently, however, I had to do a Unity project from scratch and I decided to write it in "the Unity way", leaning heavily on the editor for getting a lot of the work done.

From this, an interesting and frequent scenario has been occurring. To wit, almost every time I get stopped by something I don't know how to do, extensive Googling reveals that nobody else on the Internet is having quite the same problem I'm having. Solving such problems becomes an arduous exercise in intuitive deduction and experimentation after exhaustive searching of the Internet for a solution.

So I thought I'd stick a few tidbits about Unity I've learned along the way that were far more difficult to find answers to than I would have expected. Some of these may seem obvious. Others, not so much. I'll add more as they crop up.

Coordinate space conversions

Problem: You have some object in your scene that has to be positioned relative to some other object in the scene. Both objects are children of completely different parents. What you want is to get one object's position converted to the local coordinate space of the other object.

Example: You want to move an object towards another object. Let's call the moving object the "source" object and object it has to move toward the "reference" object.

What you want in this case is the reference object's position but converted to the same local coordinate space as the source object.

Solution: Use the Transform.InverseTransformPoint() function to do this easily, as follows:

Vector3 targetPosition = sourceObj.transform.parent.InverseTransformPoint(referenceObj.transform.position);

You can then modify "sourceObj.transform.localPosition" as necessary until it equals targetPosition, at which point sourceObj will occupy the same screen position as referenceObj.

Why it works: "obj.transform.localPosition" gives you the position of "obj" relative to its parent. "obj.transform.position" gives you the position of "obj" in world space. InverseTransformPoint() returns the position of a world space coordinate in the transform's local space. The above line of code takes the world space position of referenceObj and feeds it into the InverseTransformPoint() function of sourceObj's parent transform. This converts the world space position of referenceObj to the local space of sourceObj's parent. Since the local position of sourceObj is in its parent's coordinate space, you will get the reference object's position in that same space.