Friday, October 5, 2012

Making use of C# extension methods in Unity3d

I recently started using C# extension methods in Unity3d and found them very helpful for my workflow, so I decided to share.  During development of my recently released game Match'n Flip my goal was to rapidly prototype new game play modes quickly, so being interrupted by small things was very disruptive.  So far I've only done very simple helper methods, but these handle things which previously broke my workflow because of small nuances.

One particularly useful extension set I created are methods to move a game object along one axis, such as move a game object along the global x axis by 5 units.  Conceptually this is a very simple operation:

transform.position.x += 5F;

is essentially all you need to do, however because Unity doesn't allow you to change just 1 element of the position Vector3, instead you need to do this:

Vector3 temp = transform.position;
temp.x += 5F;
transform.position = temp;

Conceptually not difficult, but writing those 3 lines can easily break your train of thought as you're working and slow down your creative process. Additionally these little snippets are annoying because you actually have to look at them a moment to see what the transform operation is, since the meat of the operation is done on a new object not related to the object you want to modify (temp Vector3 local variable vs the position vector3 transform property).

To reduce these brain train killer situations, I created a set of ShiftPosition transform extensions methods to handle the annoying part of these operations.  Using these I can do the same operation as above one neat line and in a way that's intuitive to see what's going on:

transform.ShiftPositionX(5F);

Under the hood the ShiftPositionX/Y/Z extensions are still modifying a temp Vector3 which is re-assigned back to the transform.position property.

Here's a small snippet of what the TransformExtensions class looks like, sorry for formatting getting hosed.  Feel free to use this in your own projects if you wish, or if this is interesting to anyone, please contact me and I'll expand on this with more helpers/details!

public static class TransformExtensions
{

#region ShiftPosition

public static void ShiftPositionX ( this Transform tran, float offsetX )
{
Vector3 temp = tran.position;
temp.x += offsetX;
tran.position = temp;
}

public static void ShiftPositionY ( this Transform tran, float offsetY )
{
Vector3 temp = tran.position;
temp.y += offsetY;
tran.position = temp;
}

public static void ShiftPositionZ ( this Transform tran, float offsetZ )
{
Vector3 temp = tran.position;
temp.z += offsetZ;
tran.position = temp;
}

#endregion ShiftPosition

}

Hope you find these useful!

No comments:

Post a Comment