Raycasthit explanation wanted.

I’m trying to make a simple script that creates a cube on the place I click on a Plane. I figured I had to do that with RaycastHit, but there are no proper examples of what I want to achieve. Can someone please properly explain raycasthits and the likes, and also on which object I have to put the script on, eg: does the raycasthit only detects hits on the object the script is attached to?

Thanks in advance.

Isn’t your question answered here ?

hitInfo will contain more
information about where the collider
was hit (See Also: RaycastHit).

var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
    Debug.DrawLine (ray.origin, hit.point);
}casting a ray.

A raycast hit is not associated with any particular object. Essentially, you provide a starting position, direction and optionally a hitmask (to filter out what you want/not want to hit), and you eventually get back a RaycastHit record containing the various information you might need, including which GameObject has been hit, along with the intersection point and normal.

In your case, you just need to create a new script, called whatever, where you will put your input & raycast logic.

In Update() you will monitor the click event from the user. When this happens, you should call a function with the following pseudo/sample code:

// create a ray going into the scene from the screen location the user clicked at
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );

// the raycast hit info will be filled by the Physics.Raycast() call further
RaycastHit hit;

// perform a raycast using our new ray. 
// If the ray collides with something solid in the scene, the "hit" structure will
// be filled with collision information
if( Physics.Raycast( ray, out hit ) )
        // a collision occured. Check if it's our plane object and create our cube at the
        // collision point, facing toward the collision normal
	if( hit.collider == yourPlaneCollider )
		Instantiate( yourCubePrefab, hit.point, Quaternion.LookRotation( hit.normal ) ); 

Hope this helps.