2

I create an emtpy game object and attach .cs file. I try to load a prefab(.obj file) on mouse click position. My code is :

    Ray ray;
    RaycastHit hit;
    public GameObject prefab;

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            ray=Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                GameObject obj = Instantiate(prefab, new Vector3(hit.point.x, hit.point.y, hit.point.z), Quaternion.identity) as GameObject;

            }
            else
            {
                Debug.Log("Physics.Raycast returns false");
            }
    }

Raycast returns false everytime.

zakjma
  • 2,030
  • 12
  • 40
  • 81

2 Answers2

4

You need to add Collider to your GameObject

For Physics3D

Description

Casts a ray against all colliders in the scene.

Physics.Raycast Script API documentation here.

For Physics2D

Description

Casts a ray against colliders in the scene.

A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported.

Physics2D.Raycast Script API documentation here.

Barış Çırıka
  • 1,570
  • 1
  • 15
  • 24
  • Òn inspector, I added box collider component. – zakjma Dec 22 '15 at 09:24
  • Try it with creating new Box with Box collider. if it works, you need to specify volume (X,Y,Z size). If your object doesn't have volume you can't raycast it. And also check your collider have same volume and starts with 0,0,0 point of your Gameobject. – Barış Çırıka Dec 22 '15 at 09:28
  • I am raycasting down from player to colliders my player is standing on and getting false. – Brad Jan 16 '22 at 13:22
3

You need to attach a 3d collider to your sprite game object to get detected by raycast.

See my complete answer here

Ashwin
  • 7,277
  • 1
  • 48
  • 70