What does the new operator do?

I see a similar question has been asked here but I still don’t get it. Can someone please give me the dummies explanation? Why did Ben need “new” at 5:44 mark of the video? He mentioned “initialize” which I take to mean “give values to something”, but why “new” when in other instances we have initialized other variables without “new”, e.g.:
float period = 2f;

Thanks.

1 Like

Welcome to the community!

Imagine this as recipes, let’s say you want to cook an apple pie but you need to follow the recipe which is; apples, crust and sugar, the recipe doesn’t say the quantities, so is up to you to experiment with them, so you grab 5 apples, 1 piece of crust and 3 tbs of sugar, after you cook it you have created an entirely new pie! It’s not the one that is in the recipe’s picture, it’s a new pie.

ApplePie _myApplePie = cook ApplePie(5 apples, 1 piece of crust, 3 tbs of sugar);

Recipes in codes are called Structs, in simple terms, they are just a bunch of variables, like a predetermined array (but not really). In this particular case Vectors are just 3 floats.

Vector3(float1, float2, float3)

But as any recipe, it’s just a guide on how to create them, but they don’t actually exist until you declare them. Following the apple pie analogy, cook equals new, you are “cooking” a Vector3, you are creating a Vector out of thin air, really powerful stuff.

With time you’ll even be creating your own recipes! Yes! You can create your own structs!

There are other types that need to be created with the “new” operator; Lists, Arrays, Classes and others are just a few examples. In simple terms, everything that is more than just one variable needs the new operator.

Hope this helps.

1 Like

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

Privacy & Terms