raycast problem while drag and drop..

hello ,
i want to drag an object on another and i am using raycast for the it…
but following code is not working as programmed it do not print the log messages as one object collide with the object using raycast…
please help me to find the error…

using UnityEngine;
using System.Collections;

public class Drag_drop : MonoBehaviour {

private Vector3 screenPoint;
private Vector3 offset;
 
 void OnMouseDown() 
 { 
 
 RaycastHit hit = new RaycastHit();
    Ray ray = new Ray();        
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);

 if (Physics.Raycast (ray, out hit)) 
        {
            Debug.Log("pew pew");
            if (hit.collider.gameObject.name.Equals("Cube"))   
            {
                Debug.Log("go brooks");
             //   BrooksCallOut.gameObject.SendMessage("gotoBrooks");
            }
        }
 
 //
 
 screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
 offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
 }
 
 void OnMouseDrag() 
 { 
 Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
 Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
 transform.position = curPosition;
 }

}

Make sure that:

  1. “Cube” has enabled collider.
  2. “Cube” is not in “Ignore Raycast” layer.

btw.
you don’t need to initialize ‘hit’:
RaycastHit hit = new RaycastHit();
because it will be overwritten by Physics.Raycast (ray, out hit)
“out” is saying exactly this.

According to documentation “OnMouseDown” is called only once when mouse is pressed. It is fine for start dragging the sphere, then if you want to drop “sphere” on “cube” You need to raycast for “cube” at onMouseUp also. But remember to turn off collisions on “sphere” if you plan to translate it with mouse, otherwise you will be always detecting sphere under mouse. Something like this pseudocode:

bool is_drag = false;
GameObject dragged_go;
Vector3 drag_start;
void OnMouseDown()
{
   dragged_go = raycastSphere();
   if( null != dragged_go )
   {
// start drag
      is_drag = true;
      dragged_go.collider.enable = false;
      drag_start = dragged_go.transform.position;
   }
}

void OnMouseDrag()
{
   if( is_drag )
   {
      //... translate sphere to current mouse position
   }
}

void OnMouseUp()
{
   if( is_drag )
   {
      // test if cube is under mouse by raycasting
      // if so then translate sphere to cube coordinates
      // else return sphere to it's original position
      dragged_go.transform.position = drag_start;
      // end drag
      is_drag = false;
      dragged_go.collider.enabled = true;
   }
}

Have no time to write it fully, but you should get the idea.