Need help understanding ScreenPointToRay

Hello friends and coders,

I am trying to instantiate a cube on the ground where I click with my mouse, but running into troubles. Its a third person game, so I am trying to raycast from my mouse click instead of from the head of my character like in a first person game.

I have been reading up on ScreenPointToRay, and I think it does what I want, but not sure.

My question is - does using ScreenPointToRay send a raycast from my camera towards the point where I clicked in the scene?

If so - any reason why this code wouldnt work?

if(Input.GetButtonDown("Place Block") && placeBlock == true)						//this will need changed
		{

			vRay = Camera.main.ScreenPointToRay(Input.mousePosition);
			
			if(Physics.Raycast(vRay, out hit,/* range, */ constructionLayer))
			{
				Debug.Log ("raycast has hit " + hit.transform.name);
				addingToConstructionLayer = true;

Its obviously not the whole code but I am trying not to overload my question with unnecessary code if at all possible. By the way, I get no errors, but nothing happens and the debug statement doesnt play.

The overload with (Ray, RaycastHit, ...) takes distance as the 3rd input. You’ve got the layer as input 3, so it’s using the layer you want to hit as the distance to shoot.

You’re got a commented out range in there, just plug in 9999 (or Mathf.infinity)?

Getting the layers set up correctly can be tricky. Try it without the layerMask (just leave out contructionLayer) to be sure it’s doing what you think. When you can mouseOver a rock and it prints “hit rock,” add the layer. To avoid a giant scrolling list, can replace the Debug.Log with hitWord=hit.transform.name where hitWord is a global.

This line interests me:

if(Input.GetButtonDown("Place Block") ..

Unless you have changed your input scheme you should be using (input.GetButtonDown(“Fire1”)) which checks for mouseOne being clicked. (This may be trivial but I’m not sure how you set it up.) I’m guessing this is the problem because you have no luck with the debug.

If it is what I am assuming, you are trying to make sure it hits something with a tag of “Place Block”, Then you would want to search tags after doing the Raycast to make sure the tag is correct:

If (hit.collider.tag == "Place Block") ....