Why Transform is automatically updating in the Start() function?

Hi.

I am following a tutorial and currently writing script to make the camera follow the player.
The code obviously works, considering that it is a tutorial, but there is a part of the code that doesn’t seem to make sense to me:

[Original Code]

public class CameraFollow : MonoBehaviour
{
    private Transform player;
    private Vector3 tempPos;

    void Start()
    {
        player = GameObject.FindWithTag("Player").transform;
    }
    // Update is called once per frame
    void LateUpdate()
    {
        tempPos = transform.position;
        tempPos.x = player.position.x;     
        transform.position = tempPos;
    }

Just to make sure my understanding, I have tried replacing the private Transform player to private Vector3 player and adjusting the corresponding parts of the script, but when I run the game, the x position of the player seems to be assigned only once at the beginning.

[Changed that I have made]

public class CameraFollow : MonoBehaviour
{
    private Vector3 player;
    private Vector3 tempPos;

    void Start()
    {
        player = GameObject.FindWithTag("Player").transform.position;
    }
    // Update is called once per frame
    void Update()
    {
        tempPos = transform.position;
        tempPos.x = player.x;     
        transform.position = tempPos;
    }

My question is, how come player.position.x is automatically updated to the current position, when player.x is not?
It seemed to make sense, as I am assigning a Vector3 to another Vector3 in the Update() function.

Any help would be great!

This is simply the difference between a reference vs a value type.

Transform is the transform of the object. It’s a reference, so each time you grab it’s value, you’re asking it to go back to the transform and grab the current x value of it’s position.

In the second example, you grabbed the value of the position. This doesn’t go back and grab the new value.

If I tell you to go to the clock in the hallway and check it’s time, you will go to the clock and come back with whatever time is on it. Each time I ask for the time, you have to return to the clock and get it’s new time.

If I tell you to go to the clock and you write down on a piece of paper what time it is, you now have that value. Then if I say, tell me what time it is and you always look back at that piece of paper, you will always give the same value.

I highly suggest reading up on ref and value types as this will be important in many parts of programming for you.

2 Likes

I see, so assigning a reference to a variable is like getting a watch that shows the time on the clock.
Thanks so much!