The New Keyword

[ANSWERED]Every time I need to change the position of a gameobject I put something like transform.position += new Vector3(-speed, 0, 0);. The thing is, I don’t even know why do I write the word new. But every time I don’t write new, I get a bug. I tried reading the microsoft documentations and I still did not get it. Can anyone explain to me why do we write the keyword new and what does it mean?

You use the new keyword to create a new object, in this case of the Vector3 class. What it does is call the constructor of the Vector3 class with the supplied parameters, and returns a new object.

This is fundamental to object oriented programming, and not something easily explained in a forum post. I suggest you take the time to read some tutorials on OOP in C#.

4 Likes

Thanks, I never realized that vector 3 is a class. That explains a lot of things now.

Actually it’s a struct but…

1 Like

it’s a struct, you still need to use the new keyword with structs but it does differ in a few ways, such as that structs do not support inheritance, structs are passed by value and not reference, so they essentially get passed around by making copies. Finally structs under most circumstances are allocated on the stack and not the heap.

1 Like

Thanks for the info!