Unity vector swizzle operations

Swizzle operators are convenient syntactic sugar for creating new vectors based on the combination of elements of other vectors. They are used in shading languages quite a lot.


This is equal to:

They make more sense if you want to do some composition like so:

GLSL allows you to supply any amount of vectors or scalars in a vector constructor, as long as the count of all elements matches the dimension of the created vector.

However, swizzling isn’t allowed in most non-shading vector libraries. So, why not write simple extension methods that give that functionality to Unity?

Well, hold on a minute. Assuming vectors of 2, 3 and 4 dimensions, there are exactly 481 swizzling combinations. Yikes. Who’s willing to write all those methods? The correct answer is “nobody”.

Rather than write each method manually, I wrote a fun little program that generates all the methods for us. The code:

The above works with C# 6.0. But, if you’re too lazy to run it (as you probably are, if you intend to use swizzling 😉 ), I have provided the generated result here (click to expand):