Raycasting from a GUI Camera

I have two cameras in my scene. One main camera acting as the player viewpoint, and a second camera pointed at quads acting as a GUI layer.

Initially I was casting rays from a touch/click point on the main camera and interacting with the world fine. However I have now added a new “Reticle” quad to the gui layer, and wish to Raycast from the reticle’s position.

The problem is when I raycast from the Reticles position as the reticle is way off screen with the other gui elements. I wish to cast a ray from the maincamera as if the reticle was on the main camera.

Create a Vector3 that is relative to your reticle as a percentage of the screen position. Assuming it’s at the center of the screen :

var reticlePos : Vector3 = new Vector3( Screen.width / 2, Screen.height / 2, 0 );
var ray : Ray = Camera.main.ScreenPointToRay( reticlePos );

This uses the Main Camera. If you want to set a specific camera :

var mainCam : Camera; // drag and drop camera in the Inspector

// somewhere in the function
var reticlePos : Vector3 = new Vector3( Screen.width / 2, Screen.height / 2, 0 );
var ray : Ray = mainCam.ScreenPointToRay( reticlePos );