Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Raycast never detects a hit

Discussion in 'Physics' started by SamuelKeller, Feb 3, 2022.

  1. SamuelKeller

    SamuelKeller

    Joined:
    Nov 9, 2020
    Posts:
    9
    For some reason, the following code never detects a raycast. I've checked the debug lines, and the other object is clearly being hit and has a collider. Additionally, the raycast is spawned from outside of the collider. Why isn't it working?

    Code (CSharp):
    1.             RaycastHit Hit;
    2.             Debug.Log("Shooting");
    3.             transform.LookAt(player, Vector3.up);
    4.             transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
    5.             Debug.DrawLine(Raycaster.transform.position/* + new Vector3(horzOffset, heightOffset, 0)*/, Armature.transform.forward * angleMult, Color.blue);
    6.             if (Physics.Raycast(Raycaster.transform.position/* + new Vector3(horzOffset, heightOffset, 0)*/, Armature.transform.forward * angleMult, out Hit, Range)) {
    7.                 Debug.Log(Hit.transform.name);
    8.                 Hit.transform.SendMessage("rayHit", myTeam);
    9.             }
    10.             alreadyAttacked = true;
    11.             Invoke(nameof(ResetAttack), timeBetweenAttacks);
     
    Last edited: Feb 4, 2022
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
    Did you look at the API reference for Debug.Line? It takes two world-space position arguments, not what you passed it. It's not Debug.DrawRay.

    Also, you should ensure you're drawing a line at the same distance you're using for the query.
     
  3. SamuelKeller

    SamuelKeller

    Joined:
    Nov 9, 2020
    Posts:
    9
    Ah, yes. I had switched them by accident. Either way, the ray is still clearly hitting the other object and not giving a response.
     
  4. SamuelKeller

    SamuelKeller

    Joined:
    Nov 9, 2020
    Posts:
    9
    EDIT: Range was set to zero. Thanks for the help.

    PSA: Set your range.
     
    MelvMay likes this.
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
    Glad you got it working. Good luck with your project. :)