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

Physics.Raycast not working as expected

Discussion in 'Scripting' started by eco_bach, Sep 25, 2017.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Referencing the documenation https://docs.unity3d.com/ScriptReference/Physics.Raycast.html I'm having a problem getting Raycast to work the way I need.
    I want to detect a hit ONLY when another object is between the Main camera and the target object (The gameObject with the following method attached)

    Code (csharp):
    1.  
    2. void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3. if (Physics.Raycast(ray, 100)) print("Hit something!");
    4. }
    5.  
    Can anyone help?
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Make sure you want to raycast from your main camera and that your main camera has the tag "MainCamera". Because you put "100" as the second argument in the raycast function, it will only check 100 units away from the camera.

    If this does not help you solve your problem, let us know what your function is doing wrong, or if it seems to be doing nothing.
     
  3. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Also, you'd currently detect if you hit the object the script is on; I think you're saying you want to check if the thing you hit is NOT the object that the script's on, so you'd have to do this:

    Code (csharp):
    1. RaycastHit hit;
    2. if(Physics.Raycast(ray, 100, out hit) && hit.transform != transform) print("Hit Something!");