Lecture 22 question/feedback

Hi! In lecture 22 of " Complete C# Unity Game Developer 2D" mr. Davidson is saying that writing a new keyword inside an update method is fine, here is a code snippet

public class FollowCamera : MonoBehaviour {

    [SerializeField] GameObject objectToFollow;

    void Update() {
        transform.position = objectToFollow.transform.position + new Vector3 (0, 0, 10);
    }
}

Correct me if I’m wrong, but from my programming exerience it seems like a bad example, because every time Unity calls an update method (every frame), an object of type Vector3 is created. I don’t know how unity handles this type of operations, but I don’t think you should do that, it just feels wrong to me.
I suggest creating an object outside update method and calling it in the method, like here

public class FollowCamera : MonoBehaviour {

    [SerializeField] GameObject objectToFollow;
    Vector3 cameraOffset = new Vector3 (0, 0, -10);

    void Update() {
        transform.position = objectToFollow.transform.position + cameraOffset;
    }
}

Just want to share my oppinion. Please, correct me if I’m wrong :sweat_smile:

Hi and Happy New Year!

You are right. Since we do not change the value of the object, we could reuse it. However, cameraOffset is a struct which consists of 3 float objects. That’s “nothing” for the computer meaning we will not notice any difference regarding the performance.

Nevertheless, your solution is perfectly fine. As for me, I would probably perfer yours over Rick’s because I agree with you: It is not necessary to create this object over and over again. :slight_smile:


See also:

1 Like

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

Privacy & Terms