The "new" operator - still not understanding

Hi all

Still trying to get my head around the “new” operator. With reference to the 2 versions of code that achieve the same thing, why is there no need for the “new” operator in the second line of code?

transform.position += new Vector3(-speed * Time.deltaTime,0,0);
transform.position += Vector3.left * speed * Time.deltaTime;

Thanks

1 Like

Hi,

Vector3.left is a static property, as such you do not need to instantiate a new instance of the struct.

In the background, a new instance will be being created for you and populated, left is just shorthand for saying new Vector3(-1,0,0).

Hope this helps. :slight_smile:


See also;

1 Like

Thanks Rob

Hopefully it will make more sense to me when once we cover Struct’s, and I revisit static’s.

1 Like

Hi,

No worries.

The behaviour is the same for structs or classes. If a class contains a static method, you won’t need to instantiate it first before you can use the method.

If the class/methods are not static, then you will need to instantiate a new instance of the object.

1 Like

Thanks

That actually made it clearer to me

1 Like

Happy to be able to help :slight_smile:

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

Privacy & Terms