Reset Transform Data

(This post is sort of reposted from Gamasutra although with some modifications).

After a week or so of using the engine I started noticing some tasks which I repeatedly needed but had no built-in support for. One of those was an easy way of resetting the local data of transforms during editing. It’s not hard to achieve and I wrote a simple menu item to do it.

public static class ResetSelectedTransforms
{
  [MenuItem("Utilities/Reset Selected Transforms &z")]
  public static void Perform()
  {
    foreach (var selected in Selection.gameObjects)
    {
      var transform = selected.transform;
      transform.localPosition = Vector3.zero;
      transform.localRotation = Quaternion.identity;
      transform.localScale = Vector3.one;
    }
  }
}

Notice that I added the ‘&z’ character to the menu item’s name; this causes Unity to associate the ‘alt+z’ shortcut to our menu and makes it easier to call it (remember: lazy is good!). And finally see that we’re resetting only the local properties of the transform, this way we’re avoiding a host of issues concerning the parenting hierarchy of the object.

Using this menu item a few times and writing more code for the game I also found that resetting transforms is something I need to do sometimes during Unity’s runtime environment (rather than just while editing – more on my building process and separation of projects in a later post). So let’s extract this into a useful utility/extension method.

public static class TransformResetExtensions
{
  public static void ResetLocal(this Transform transform)
  {
    transform.localPosition = Vector3.zero;
    transform.localRotation = Quaternion.identity;
    transform.localScale = Vector3.one;
  }

  public static void ResetGlobal(this Transform transform)
  {
    transform.position = Vector3.zero;
    transform.rotation = Quaternion.identity;
    // Unity hasn't exposed a setting on the lossy scale;
  }
}
“Truth is I haven’t played much since the baby came in June, but give me half a minute and I’ll get this fiddle back in tune.”
Advertisements
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s