How do extension methods work?

First, here's a very quick tutorial on extensions for those learning c#/Unity for anyone googling here:

Make a new text file HandyExtensions.cs like this ... (note that somewhat confusingly, you can use any name at all for the class which "holds" your extensions - the actual name of the class is never used at all, and is irrelevant) ...

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public static class HandyExtensions
     {
     public static float Jiggled(this float ff)
         {
         return ff * Random.Range(0.9f,1.1f);
         }
     }

You have now made a new "command" Jiggle(). You can use jiggle on any float. See where it says "this float ff". Because it says "float" just there, this extension works on floats.

As you can see, the Jiggled() extension will take a float and change it slightly. Try it like this

 float x = 3.5f;
 Debug.Log("x is " + x);
 Debug.Log("x is " + x.Jiggled() );
 Debug.Log("x is " + x.Jiggled() );
 Debug.Log("x is " + x.Jiggled() );
 Debug.Log("x is " + x.Jiggled() );
 Debug.Log("x is " + x.Jiggled() );

Do some tests like that until you have a good understanding of extensions. Learn as much as you can about extensions! Here's another tutorial.

And now the question on this page! ...


As Mikael explains, what you are looking for is not actually an extension. (Also note, if you're trying to add a field to Vector3, you cannot do that in c#.)

Now, if you want to return "that thing" you need to include the static class name up front, and you DO NOT make it an extension. It's just a normal call to a static.

wrong...

public static Vector3 MaxValue(this Vector3 _vec3)
{
    return new Vector3(float.MaxValue,float.MaxValue,float.MaxValue);
}

correct...

public static Vector3 MaxValue()
{
    return new Vector3(float.MaxValue,float.MaxValue,float.MaxValue);
}

you can then do this ...

Debug.Log(   ExtensionMethods.MaxValue()  );

I think that may be what you're looking for there.

You'd normally call ExtensionMethods something short like Handy so you can write

 Handy.MaxValue();

indeed, since you can't put the "Vector3 up front", something like this would be more clear:

  Handy.MaxVector3();

makes sense?

If you're trying to write something like this: Vector3.MaxValue() you can't do that ... because the "Vector3" part IS A CLASS (or Struct), not a variable. For example, this is an extension on an integer:

 375.Jiggle();

and this is an extension on an integer:

 int x;
 x.Jiggle();

but this is meaningless:

 int.Jiggle();  // meaningless

To repeat for clarity, note that you asked:

I want to make an extension method in Unity3d for the Vector3 class [actually a struct]

extensions can only be called on actual variables, not on "the class or struct".

   Vector3 hero;
   Vector3 enemy;
   hero.Jiggle();  // works great
   enemy.Jiggle();  // works great
   
   Vector3.Jiggle();  // syntax error - meaningless

Note too that as Mikael actually mentions in his answer, you can in fact actually do this:

  (new Vector3()).Jiggle();

If you think about it that makes sense, too. One of my favorite things in c# is that you can use extensions on plain old constants:

 14.Jiggle();
 7.5f.Radians();

You've got to love that unless you just get no pleasure from life. Here's an example of that:

public static Color Colored( this float alpha, int r, int g, int b )
    {
    return new Color(
        (float)r / 255f,
        (float)g / 255f,
        (float)b / 255f,
        alpha );
    }

You can then write .. Color c = .5f.Colored(.2f,.4f,.2f); and that is a pucey color with an alpha of .5f.

I've always thought it would be great if the syntax you ask about was available, if you could have a "type" or "class" somehow as the "thing" you extend on - but it's not the case. For what you are trying to do, you have to just use a handy word such as, well, Handy, and do this

Vector3 big = Handy.MaxVec3();

I hope this explains the situation!


Again for anyone needing a general intro to extensions, intro. Here are some of my favorite extensions.

Something like the following is used in every game project...

public static float Jiggle(this float ff)
    {
    return ff * UnityEngine.Random.Range(0.9f,1.1f);
    }

public static float PositiveOrNegative(this float ff)
    {
    int r = UnityEngine.Random.Range(0,2);
    if (r==0) return ff;
    return -ff;
    }

public static bool Sometimes(this int n)
    {
    if (n<=1) return true;
    int r = UnityEngine.Random.Range(0,n);
    return (r==0);
    }

Example uses..

 if ( 10.Sometimes() )
   {
   explode spaceship
   }

it only does it once in ten times.

 if ( 3.Sometimes() )
   {
   laser sparkle
   }

in that example it only does it about a third of the time.

(Note that indeed typically you make extensions use generics where possible. Not shown here for simplicity.)

Here's a handy extension trick. Here's a really advanced extension.

Extensions are ubiquitous in Unity engineering.

If you are one of the many folks learning to code using Unity...pretty much the first thing you should master is extensions. Try to do almost everything with an extension. Sometimes when working with Unity, almost every line of code needs one or more extensions. Enjoy!


Extension methods is a way to make it look like static methods are part of a class or interface. An extension method Foo() on Vector3 means you can do new Vector3().Foo() just like you say.

It looks like you'd like your MaxValue property to be a static member on Vector3, and extension methods can't help you there. There's no way to add static members to an existing class.

But, is it really necessary? You can just define your constant property in a new type. Let's call it "KnownVectors" or something, and go:

Vector3 closestPoint = KnownVectors.MaxValue;

Sure, maybe it would be nice to shoehorn this into the existing Vector3 class somehow, but would it really add anything to your code?