Skip to content

Instantly share code, notes, and snippets.

@WardBenjamin
Created June 26, 2016 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WardBenjamin/1b4e8759b25f839d0db1e027b003ebf7 to your computer and use it in GitHub Desktop.
Save WardBenjamin/1b4e8759b25f839d0db1e027b003ebf7 to your computer and use it in GitHub Desktop.
Unity Transform extension method to make setting position less painful
using UnityEngine;
public static class TransformEXT
{
public static void SetPosition(this Transform transform, float x = float.NaN, float y = float.NaN, float z = float.NaN)
{
var pos = transform.position;
if (!float.IsNaN(x))
pos.x = x;
if (!float.IsNaN(y))
pos.y = y;
if (!float.IsNaN(z))
pos.z = z;
transform.position = pos;
}
}
Usage Example:
If GameObject.transform.position is 0, 0, 0:
GameObject.transform.SetPosition(5, 10, 4); // pos is now 5, 10, 4
GameObject.transform.SetPosition(5); // pos is now 5, 0, 0
GameObject.transform.SetPosition(x: 5); // pos now 5, 0, 0
GameObject.transform.SetPosition(y: 10); // 0, 10, 0
GameObject.transform.SetPosition(y: 10, z: 4) // pos now 0, 10, 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment