Linecast detecting collision from target

Pretty simple question, I have no idea what a solution would be though. Im just trying to make a simple linecast, that goes from an AI to my player. At the moment, Im just trying to make it so if it detects a collider on the way to the target, it feeds back “Collider”, and if not, “No Collider”. Pretty simple. But the issue is, it seems its including the collider around my player as a collider thats blocking the line. If I turn the collider off, which I obviously wouldnt want to be in game, then it works.

Heres the code

#pragma strict
var PlayerTarget : Transform;
var TestState : String;

function Start () {

}

function Update () {

Debug.DrawLine (transform.position, PlayerTarget.position, Color.red);


if (Physics.Linecast (transform.position, PlayerTarget.position)) {
			TestState = "Collider";
}

			else{
			TestState = "No Collider";
			}
}

(I use a string rather than Debug.Log just because its easier for me to read when theres a lot of stuff in the debug log)

According to the docs of Physics.Linecast, you can give a third argument called LayerMask which: ‘is used to selectively ignore colliders when casting a ray.’

By using that argument, and putting your AI/Player in the correct layer you can fix your problem.

The most simple solution would be to set your player’s GameObject’s layer to “IgnoreRaycast” if possible (it would work if you’re not putting it on a particular layer for some reason, and you don’t need to raycast against the player for any other reason).

Another would be to set up a custom LayerMask for your Linecast, and have it ignore the player’s layer. This page (Unity - Manual: Layers) has some info that can help, but here’s a snippet:

// Bit shift the index of the layer to get a bit mask
// Assumes that the player is on a layer called "Player"
int layerMask = 1 << LayerMask.NameToLayer("Player");
    
// This would cast rays only against colliders in the "Player" layer.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;

RaycastHit hit;

if (Physics.Linecast (transform.position, PlayerTarget.position, out hit, layerMask))
{
    // etc...
    // You can use "hit.collider" to get the other collider and GameObject