Circling back to using "new"

Would it be possible to have 1 module dedicated to the use of “new”.

I know that new is used to allocate a space in memory for the variable of whatever type. But what happens to the “old” assignment. I am struggling with when to use “new”. For example in the Waypoint script, “new” is used in a return statement, but at that point it is not even assigned to a variable, but will eventually be assigned to a calling method.

“return new Vector2Int
(
Mathf.RoundToInt(transform.position.x / gridSize) * gridSize,
Mathf.RoundToInt(transform.position.z / gridSize) * gridSize
);”

So if I wanted to return a spefic Vector2Int why could i not write
return Vector2Int(0,10). I already know this doesn’t work (I tried it), unless I put “new” in, but I don’t know why. And why do we put the “new” in the return statement rather than the calling method e.g. “public new Vector2Int GetGridPos()”.

I know what “new” is meant to do - but I don’t yet understand when or where it should be used - at least not all the time. Hopefully the above will spark an AHA in someone on the forum who can reach into the way I am looking at this and help me correct the way I am looking at it.

Privacy & Terms