Raycast to select tiles not working

I have made a raycast to try and select tiles, but every time it is fired it doesnt hit anything. Can anyone see what the problem is?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SelectionManager : MonoBehaviour {

    public static SelectionManager me;

    [SerializeField]
    GameObject currentlySelected;

    [SerializeField]
    TileMasterClass[] objectsWithSuperClass;

    void Awake () {
        findAllSuperClassExamples();
    }

    void Start () {

    }

    void Update () {
        checkForLeftMouseClick ();
    }
    public void setSelected(GameObject toSet)
    {
        currentlySelected = toSet;
        currentlySelected.GetComponent<TileMasterClass> ().OnSelect ();
    }
    public GameObject getSelected()
    {
        return currentlySelected;
    }

    void clearSelected()
    {
        currentlySelected = null;
        Debug.Log ("Cleared Currently Selected");

    }

    void checkForLeftMouseClick()
    {
        if (Input.GetKeyDown (KeyCode.Mouse0)) {
            Debug.Log ("Clicking, looking for raycast hits");
            selectionRaycast ();
        }
    }

    void selectionRaycast()
    {
        Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint (Input.mousePosition).x,Camera.main.ScreenToWorldPoint (Input.mousePosition).y);

        RaycastHit2D raycast = Physics2D.Raycast (mousePos, Vector2.zero, 0f);

        try {
            GameObject hitObject = raycast.collider.gameObject;
            Debug.Log (hitObject.name);
            setSelected(hitObject);
        }
        catch {
            Debug.Log ("Raycast Missed");
        }

    }

    void findAllSuperClassExamples()
    {
        objectsWithSuperClass = FindObjectsOfType<TileMasterClass> ();

    }

}

On line 55 when you declare the Raycast you’re setting its direction and distance to zero so the Raycast won’t be traveling anywhere. Check this page: Unity - Scripting API: Physics2D.Raycast to see the parameters for the Physics2D,Raycast function. Also, as a side note, on line 53 when you get the mouse position, you don’t need to make a new Vector2. You can just do Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

1 Like