Vector Utilities for Unity - Make Helsinki

Vector Utilities for Unity

by: Davor Skontra
  •   Development •  17.3.2020   •  3 minute read

Utilitarian Life, Chapter I

All programmers have utilities they find themselves writing over and over again into almost any project they work on. Some of these utilities will end up in common boiler-plates shared with the whole company and some will only ever be loved by the developer who wrote them. This is a first post in a series of posts where programmers from Make Helsinki write about Utilities that make their days more efficient and their code easier to read.

If you read and/or write a lot of Unity code, you will often encounter something resembling this.

// Get position with fixed height specified by desiredHeight field
var fixedY = new Vector3(transform.position.x, desiredHeight, transform.position.z);

or

// Get position with height adjusted by amount specified by adjustment field
var adjustedY = new Vector3(transform.position.x, transform.position.y + adjustment, transform.position.z);

 

The above are two quite verbose ways of saying, “I’d like this position, but change the height to something else.”

Personally I prefer an another way. A static utility class with some extension methods can make this much cleaner.

// Get position with fixed height specified by desiredHeight field
var fixedY = transform.position.WhereY(desiredHeight);

As you can see, this line is much shorter because you don’t have to get a reference to transform.position three times. Once is enough.

This method has another cool overload

// Get position with height adjusted by amount specified by adjustment field 
var adjustedY = transform.position.WhereY(y => y + adjustment);

This way, you can use an original value and modify it for the resulting Vector.

Here’s the source code

Click the image to view the code on GitHub.

Click the image to view the code on GitHub.

As you can see, the class has a bunch of extension methods, allowing you to create modified copies of any of the native Unity vector types. Providing both overloads for any of the Vector properties you might want to change. X,Y,Z and even W for Vector4.

As stated above you can get the source from here. Feel free to use this utility anywhere you want, I’ve developed it on my own time and everything in that repository is  MIT licensed.

If you’d like to read some other game development related articles, I’d like to recommend this one about the difference when developing games today vs 20-30 years ago.

And lastly, if you’d like to know more about how we at Make Helsinki relax after hours, click here.

 

Leave a Reply

Your email address will not be published. Required fields are marked *