Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Using Raycast to Select Objects

Discussion in 'Scripting' started by Mechan1cal, Nov 15, 2017.

  1. Mechan1cal

    Mechan1cal

    Joined:
    Nov 15, 2017
    Posts:
    12
    I hope this is the right part of the Forums.

    I'm trying to make a raycast in a 2d game that will select the tiles it hits. The raycast seems to be firing, but it never hits anything. The catch statement always triggers, but never the try.

    The Code:

    Code (CSharp):
    1.     void selectionRaycast()
    2.     {
    3.         Vector2 mousePos = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
    4.  
    5.         RaycastHit2D raycast = Physics2D.Raycast (mousePos, Vector2.zero, 0f);
    6.         try{
    7.  
    8.             GameObject hitObject = raycast.collider.gameObject;
    9.             Debug.Log(hitObject.name);
    10.             setSelected(hitObject);
    11.             Debug.Log ("Hit...Something");
    12.  
    13.         }
    14.         catch{
    15.             Debug.Log ("No Valid Objects Selected");
    16.         }
    17.     }
    Can anyone see what the issue might be? Thanks.
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    The second argument is the direction to fire the raycast. You've essentially given it no direction (and no distance for that matter). Try passing Camera.main.transform.forward and something else besides 0 (or omit it for infinity) for distance and see if that helps.

    Also - it's generally not a good idea to use try-catch to control the logical flow of your code. You can just check the collider before proceeding

    Code (csharp):
    1.  
    2. if (hit.collider != null)
    3. {
    4.  
    5. }
    6. else
    7. {
    8.     Debug.Log("nothing hit");
    9. }
    10.