- Home /
C# - Unity "this" is an unexpected symbol
Now, I am not a complete beginner with C# and know a BIT of java andjavascript, however, this is highly confusing. I am trying to create a custom character controller in C#, but it is not liking what I have put. Can anyone fix this? or even find a better way of doing this?
void Movement() {
if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")) {
moveDirection = Vector3(Input.GetAxisRaw("Horizontal"), moveDirection.y, Input.GetAxisRaw("Vertical"));
this.transform.Translate(moveDirection * speed) * Time.deltaTime);
}
}
'this' is unnecessary in this case, AFAI$$anonymous$$ the this keyword will refer the component or script instance on an object, in this case. For example if you call Destroy(this) it will remove this script instance from the object.
Lowercase transform is already a direct reference to this scripts attached gameobjects transform so you don't need to write this. Just transform.Translate(...) will work fine.
Also I thought setting a vector manually requires the new keyword which you seem to be missing when setting moveDirection
Answer by aldonaletto · Nov 22, 2013 at 10:02 PM
this.transform is valid in Unity: this refers to the script, which isn't a GameObject (class where the property transform is defined), but an interesting feature in Unity allows direct access to GameObject properties from any of its components (no idea how they do it) - this.transform thus does the same as gameObject.transform or just transform. From the code posted, the problem seems to be an extra closing parenthesis after speed - just remove it:
this.transform.Translate(moveDirection * speed * Time.deltaTime);