NEW keyword

I would like to know why we don’t use ‘new’ for vector 2 in CalculateWorldPointOfMouseClick(). I know new is used to tell that we are creating a new instance of the object and as we are using vector3 struct/class, we must use new there. So why are we using new in SnapToGrid() but not in CalculateWorldPointOfMouseClick().

	public Camera gameCamera;
	public GameObject defendersParent;

	void Start(){
		defendersParent = GameObject.Find ("DefendersParent");
		if (!defendersParent) {
			defendersParent = new GameObject ("DefendersParent");
		}
	}

	void OnMouseDown(){
		GameObject newDefender = Instantiate(Button.selectedDefender,SnapToGrid(CalculateWorldPointOfMouseClick()),Quaternion.identity) 
										as GameObject;
		newDefender.transform.parent = defendersParent.transform;
	}

	Vector2 SnapToGrid(Vector2 worldPos){
		float newX = Mathf.RoundToInt (worldPos.x);
		float newY = Mathf.RoundToInt (worldPos.y);
		return new Vector2 (newX, newY);
	}

	Vector2 CalculateWorldPointOfMouseClick(){
		float mousePositionX = Input.mousePosition.x;
		float mousePositionY = Input.mousePosition.y;
		float distanceFromCamera = 10.0f;

		Vector3 worldCoordinates = new Vector3 (mousePositionX, mousePositionY, distanceFromCamera);
		Vector2 worldPosition2D = gameCamera.ScreenToWorldPoint (worldCoordinates);

		return worldPosition2D;
	}
}

Hello Naumaan,

I think the two specific lines of code you are referring to are these;

From SnapToGrid;

return new Vector2 (newX, newY);

From CalculateWorldPointOfMouseClick;

Vector2 worldPosition2D = gameCamera.ScreenToWorldPoint (worldCoordinates);

In the first, you are creating a new instance of a Vector2, passing newX and newY to it’s constructor. In the second, you are declaring a variable which receives a new Vector3 as the return type from the ScreenToWorldPoint method.

You might now be thinking, “Hang on, you said Vector3”, that’s correct. If you look at the documentation for ScreenToWorldPoint you will see that it returns a Vector3. Your Vector2 variable, worldPosition2D effectively ignores the Z value from the Vector3 it receives.

Hope this helps :slight_smile:


See also;

Ok so ScreenToWorldPoint is returning value as new , we need not specify it.

1 Like

That’s correct, ScreenToWorldPoint is taking in the values you give it, it then calls the constructor for a new Vector3, and returns it. As such you only need to declare a variable to hold that reference as opposed to instantiating new instance yourself.

Thanks for the help.

You’re very welcome Naumaan :slight_smile:

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

Privacy & Terms