Extend Unity classes like Vector3 & Transform with Extension Methods

Wrote a quick post explaining extension methods for people who are new to them. Also included some of the ones I use and links to a couple other good resources.

If anyone has more great extension methods they want to share, post here, would love to link them.

2 Likes

thank you very much! I still have trouble understanding them :confused: I have this method:

public static class ExtensionMethods {

public static float Remap (this float value, float from1, float to1, float from2, float to2) {
return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
}
}

and I just do no understand how to call remap in another script. this does not work for for example:
print(Remap(1.0f, 3.0f, 0.0f, 10.0f));

could you point me in the right direction?

You’d probably have the best luck looking at standard C# explanations and examples. There’s no difference between how extension methods work in regular C#, and in Unity C# (I found everything I needed to write working ones in the standard C# docs.)

That’s one of the main things to know: if something is a general programming topic, or general C#, the best explanations are usually in general sites. The Unity site works best for Unity-specific topics.

1 Like

Since this question has been a long way ago…
But for maybe someone still do not get the point you mentioned. So …
It seems like you are not actually understand the way it goes… (sry for my straight words
The true way you call the funcion you define at ExtensionMethods class called Remap is :

float theFloatUWannaRemap = 0.0f;
print(theFloatUWannaRemap.Remap(1.0f, 3.0f, 0.0f, 10.0f));

same :

print((0.0f).Remap(1.0f, 3.0f, 0.0f, 10.0f));

Any way to add an extension to the Vector3 class itself?
Such as the Vertor3.Lerp() method?

That example is working if affecting this Vector3.

Doesn’t really make sense. Extension methods are just syntax sugar that effectively just pass in the instance as the first argument of the method. Technically speaking this is true of all instance methods, too.

You can’t have an extension for the class, or in this case, the struct, itself, as there is no instance to work with. The class/struct is just the definition for the actual object. Methods like Vector3.Distance are just static methods that happen to be in the Vector3 struct for API convenience. They could’ve been in another static class if someone at Unity decided to do that 10 or so years ago. And you can’t add new methods without changing the code itself, which we naturally can’t do for Unity’s own code.

If you want your own general Vector3 related methods, then you need your own static class for that. We all have one.

Thanks!
Just wondering cause I got that custom Vector3.LerpAngle and some others which would have been more convenient to be part of the Vector3 class…
A bit unfortunate!