About the new keyword

I’m new to programming in general, and I wanted to ask about the new keyword. I saw it’s being used in this lecture, but I never got an explenation for it. I tried to search for it online, but the answers seem super complicated for me, so is there is dumbed down explenation that someone could give to me about it? It’s just a missing puzzle piece for me to wrap my head around it.

new creates a new instance of the type. new Vector3(); - for example - creates a new instance of Vector3. Some types require more information in order to be created. The above will create a new Vector3 with x, y and z all set to 0. new Vector3(10, 20, 30); will create a new instance of Vector3 with x = 10, y = 20 and z = 30 because this specific constructor of Vector3 takes those values.

Not quite sure what more you’d like to know. Feel free to ask

Yeah, that’s all I wanted to know, I just didn’t know when and where it should be used. This is pretty self-explanatory, thank you very much. It’s just weird it didn’t need to be used until now. :smiley:

We shouldn’t use it for things like MonoBehaviour and ScriptableObject. Unity doesn’t like it. For those we use Unity’s Instantiate. In Unity, most of the instances you would want is already available. A lot of the time we use something like Vector3.zero which is a reference to an existing instance that we can use.

In normal C#, we would use the new keyword more often.

However, as bixarrio mentioned, Unity comes with its own rules. When working with Unity classes, we rarely use it. For structs such as Vector3, we do use it. (I currently don’t know if there is any exception.)


See also:

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

Privacy & Terms