Raycast if-statement does not work

I am currently fixing the last part of an enemy AI so it won’t try to shoot the player through walls. I have attempted to do this by having a raycast go from the enemy to the player detecting if there is something in between but for some reason, it does not work and I really have no idea why. Anyone out there who could shed some light on this problem?

RaycastHit hit;

private void Update()
{
playerInRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (Physics.Raycast(shootPos.position, (player.position - transform.position), out hit, attackRange) && hit.transform.CompareTag("Player"))
{
//DOES NOT REACH HERE
Debug.Log(hit.transform.tag);
agent.enabled = false;

AttackPlayer();
}
else
{
if (agent.enabled == false)
{
agent.enabled = true;
}
ChasePlayer();
}

}

i’d think this part fails, since it hasnt done the hit result yet? try if you put it before the debug.log line

&& hit.transform.CompareTag("Player")

Already tried. There is nothing inside of the “hit” variable even after the first if statement.

is it hitting something thought? (try print hit.transform.name)

Hmm, it does actually hit the player sometimes if you stand in certain spots but most of the time the raycast seems to hit the floor or random objects even if the player object is right in front.

Do you get any errors ? Did you set the “RaycastHit” in the inspector or did you already check, which result your statement returns ?

Maybe try the following, to see if you get true:

Debug.Log(hit.transform.CompareTag("Player"));

Just found the error. Was just me being stupid. There was a typo in the tag. (Plaeyr instead of Player).

1 Like