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);
}
}
}
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:
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.
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
}