Why don’t we need new when creating paddleToBallVector?

Hi! This has been asked a few times here, but I’m still a little unclear on it…it seems like there are a few ways to declare a new Vector2 variable:

public class BallController : MonoBehaviour
{
    [SerializeField] PaddleController paddle1;

    **// Here, the paddleToBallVector Vector2 is declared like any variable**
**    Vector2 paddleToBallVector;**

    void Start()
    {
        paddleToBallVector = transform.position - paddle1.transform.position;
    }

    void Update()
    {
        **// Here, the paddlePos Vector2 variable is declared with the new Vector2 syntax**
**        Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);**
        transform.position = paddlePos + paddleToBallVector;
    }
}

What’s the difference here? Is it about what you want to eventually do with the vectors? For example, paddleToBallVector is fed other vectors as values, whereas paddlePos is fed separate coordinates for x & y?

Thanks in advance!

Hi,

In pure C#, we would use the new keywords to create a new object with a constructor. A constructor is a special method creating a new instance/object of a class. The name of the method is the same as the classname, e.g. Vector2().

Since Vector2 is a struct, which is a value type, it always has a default value. For this reason, it is not necessary to create a new Vector2 object to initialise the paddleToBallVector variable.

A variable of type Vector2 only accepts an object of type Vector2, not floats or something like that. The struct consists of two floats (and other things), x and y. We can assign our own values to those fields.

new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);

creates a new Vector2 object with the values that we passed on in the parentheses.

Is this what you wanted to know?


See also:

Hey Nina,

Oh man, thanks for the explanation. I think that makes sense. Just to make sure I’ve got it, would this code represent two ways of creating identical Vector2 variables from the same reference?

Vector2 myCoolVector;
myCoolVector = myCoolGameObject.transform.position;

Vector2 myOtherVector = new Vector2(myCoolGameObject.transform.position.x, myCoolGameObject.transform.position.y);

You are creating two different Vector2 objects with your code but they have the same values. The difference is crucial because, as aforementioned, Vector2 is a value type. We (or rather “C#”) create new objects when we assign a Vector2 object to a Vector2 variable.

Ok, that’s exactly what I wanted to know. Thanks for the help!!

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

Privacy & Terms