transform.position vs this.transform.position
``
Are this two the same?
What is “this.” for?
When is useful or correct to use “this.” ?
transform.position vs this.transform.position
``
Are this two the same?
What is “this.” for?
When is useful or correct to use “this.” ?
“this” refers to the instance of the class the statement is in. It is always implicitly there - there is no point in explicitly writing “this.”. The only time there is a difference is when there is both a local and a global variable of the same name in the same scope. In this case, this.name will refer to the global “name” variable, whereas just “name” will refer to the local one. However, I would generally advise you to name global and local variables differently, as this prevents confusion and improves code readability. (private fields should start with an underscore, public ones with a capital)
Otherwise, you will use “this” mostly to pass a reference to the object itself to other objects, or to refer to itself in any other other way. For instance, Destroy(this) to destroy the behaviour.
Sometimes its useful for ensuring you are targeting the correct variable as well… ie
float speed = 0;
void UpdateSpeed(float speed)
{
this.speed = speed;
}
If I typed the above as…
float speed = 0;
void UpdateSpeed(float speed)
{
speed = speed;
}
It wouldn’t know which was which since they are identical in name and type. Granted this is code you generally want to avoid, but it happens.
Im more likely to use ‘this’ to pass a reference to another script…
public class ClassA()
{
public ClassA()
{
ClassB b = new ClassB();
b.SetReference(this);
}
}
public class ClassB()
{
ClassA referenceA;
public void SetReference(ClassA reference)
{
referenceA = reference;
}
}
I often see this type of code used in constructors. In constructors in particular it makes a lot of sense for the variables passed in to have the same name as the classes public fields.