Question about Player Movement

In this lesson i learn that for moving the player sprite to the left i should use:

	if (Input.GetKey(KeyCode.LeftArrow)){
		transform.position += new Vector3(-speed * Time.deltaTime,0,0);

but i can perfectly use instead this.transform.position… and gameObject.transorm.position… but i cannot use GameObject.transform.position…

my question are:

  1. why they teach me to use transform.position, and why is it better (if it really is) than this and gameObject?
    2)why i cannot use GameObject?
1 Like

Hello @marioylink11, how are you?

I will start answering the second question:

GameObject is an class, class is kind of an blueprint for an entity, from this class you have many behaviours but most of them require an instance of the class to be executed. Instances are objects of the type of the class but that actually “exists” and are unique in the memory, for example, you could say that we are instances of the class Human. The class Human wouldn’t be able to hold an hammer for example, because it is an type and not an instance, but we(as unique humans made accordingly to the type Human) would be able to hold an hammer since we are instances.

gameObject is an an variable that returns the instance of the GameObject running it, you can say gameObject.transform because it exists in the memory (in this case it is the actual GameObject that your script is component of), you can’t say GameObject.transform because GameObject is the type and it doesn’t exists as an unique instance in the memory. GameObject.transform would be more or less the same as saying Human(whole race) picked up the hammer(single object), which wouldn’t make sense.

Back to question one:
position is an Vector3 of the class Transform, you can access it by typing transform.position because within an monobehaviour the variable transform returns the Instance of the Transform bound to the GameObject running the code. “this” is an keyword that references the own script instance running the code. So you already have an reference to the transform from within the script you are writing, saying this.transform is redundant and gameObject.transform is redundant too because the Transform bound to the script is the same instance that is also Bound to the script’s GameObject.

It was a bit confusing, I hope you understand it xD

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms