RaycastHit2D Not Working

I’m using a ray as a line of sight for one of the bosses in my game, but the ray won’t work at all.

Here’s the script holding the ray:

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

public class V2GuardLOS : MonoBehaviour
{
    public float distance;

    // Update is called once per frame
    void Update()
    {
        RaycastHit2D lineOfSight = Physics2D.Raycast(transform.position, transform.right , distance); // make a ray to detect if our player has entere the boss room
        if (lineOfSight.collider != null) // if our ray hits something...
        {
            Debug.DrawLine(transform.position, lineOfSight.point, Color.red); // draw a line in scene view
        }
        else
        {
            Debug.DrawLine(transform.position, transform.position + transform.right * distance, Color.green);
        }
    }
}

Debug.DrawLine will only be shown in the game-view window when Gizmos are enabled.
Be sure to enable Gizmos on the game-view window if you haven’t.

1 Like

I tried that and still nothing. Am I doing anything else wrong?

Check the following:

  • Did you add the script to a GameObject in the scene?
  • Is the GameObject enabled?
  • Is the script enabled?
  • Is the “distance” field greater than 0? (Is it a large enough number in general to be seen?)

I’ve put the script on the GameObject I want to shoot the ray from, I checked if the GameObject and script are enabled, and the distance is 50, as shown here:
Is it that I have the GameObject prefabbed?

Make an empty scene, add an empty game object, add this script, turn it sideways so you can see the ray, press play.

If that doesn’t work, stop there and figure out why. See above. Strip it down, just do ONLY the Debug.DrawLine()… In fact, I just did this with your unmodified script above, put it on a blank GameObject at (0,0,0) rotated (0,45,0 and it works:

6772249--782944--Screen Shot 2021-01-27 at 11.11.03 AM.png

So we know it works, strip EVERYTHING else out, PROVE that what you think is failing (the drawline) is actually failing. I don’t think it is. Isolate, delete, isolate, remove, isolate… basic engineering 101.

1 Like

Thank you for this! Using this method, I’ve found that the game object that this script is for is causing problems. The ray itself is working 100% as expected.
If anyone would like this for reference, here’s the solution I found with this method:

    private void Start()
    {
        Physics2D.queriesStartInColliders = false; // the ray no longer detects it's own collider
    }
2 Likes