Hi, I am currently learning Extension Classes and from what I could undertand :
You have to create a name space, then a static class and a static function, the keyword this is used in the parameter of the extension function, but I don’t understand where we say of which class it is an extension.
Namespace A{
public static class GameObjectExtensions
{
public static void NewTrick (this GameObject go, Vector3 pos)
{
go.transform.position = pos;
Debug.Log(go.name);
}
}
this GameObject go
“this” is telling unity that it is an extension, (here we want it to be an extension of Gameobject class) but just after that we say GameObject go, here we can see that GameObject belongs to go, it is its type.
So where do we say what it is the extension of ? I don’t understand, or I am missing something…
Thank you very much
You don’t have to create a namespace to use extension classes.
It is an extension of the class which you use the ‘this’ keyword on. So in your example, it is an extension of GameObject (although it seems kinda pointless tbh).
GameObject doesn’t belong to go. go is just a reference to an actual GameObject. go is not a type. The type of GameObject is GameObject.
I was trying to do this in another class.
I still don’t understand, if you have another class and do all the stuff, how does it know of what class it is an extension of ?
Well really, extension methods are just syntactic sugar. So when you do this:
public static void NewTrick(this GameObject go, Vector3 pos){
go.transform.position = pos;
}
It is the exact same as this:
public static void NewTrick(GameObject go, Vector3 pos){
go.transform.position = pos;
}
The end result is the same but the syntax is a bit different. To use the former, you would do this:
gameObject.NewTrick(Vector3.zero);
The latter:
NewTrick(gameObject, Vector3.zero);
Thank you, if I understood right :
“(this GameObject go)”
Ok, so here the word (gameObject) after “this” keyword tells of which class it is an extension.
But GameObject also defines the type of “go”.
So GameObject is used twice ?
But this is causing a flexibility problem…
go is not a type. It is a variable.
You could do this:
public static void Attack(this GameObject attacker, GameObject defender){
// Do Stuff
}
then you would just do
gameObject.Attack(otherGameObject);
So what type is attacker here ?
attacker is a GameObject.
So GameObject also defines the type of attacker.
But it is still flexible as you can still put another argument and not use the first.