- Home /
AI raycasting problem
I have a rudimentary AI.
I also have a problem.
My AI has a script that first checks if a player is in a trigger collider, in this case a cone mesh, then if the player is in it, the script, in it's update method, raycasts to the player to see if the player is truly visible.
Unfortunately, on the line that i raycast, line 19, has a null reference exception that I can't seem to fix
Here is my code:
using UnityEngine;
using System.Collections;
public class ViewPlayer : MonoBehaviour {
public Collider[] objectshearable;
public float hearRadius;
public bool isPlayerSeeable;
public GameObject player;
public float dist;
public bool playerLOS;
void Update () {
objectshearable = Physics.OverlapSphere(transform.position, hearRadius);
//if the player is in the cone of sight, the script checks the player not blocked by walls
if (isPlayerSeeable == true)
{
RaycastHit hit;
Physics.Raycast(transform.position, player.transform.position, out hit);
//if the thing it hits is the player, with nothing between
if (hit.collider.tag == "Player")
{
//the player is in the line of sight
playerLOS = true;
Debug.Log("i see you");
}
//if there is something between the player and the wall
if (hit.collider.tag != "Player")
{
//the player is not in the line of sight
playerLOS = false;
Debug.Log("i can't see you");
}
}
}
//if in fov
void OnTriggerEnter(Collider col)
{
if (col.tag == "Player")
{
Debug.Log("in collider");
//the player may be in line of sight; the player is in cone of sight
isPlayerSeeable = true;
}
}
//if not in fov
void OnTriggerExit(Collider col)
{
if (col.tag == "Player")
{
Debug.Log("not in collider");
//the player is not in the cone of sight, the AI dosen't do anything
isPlayerSeeable = false;
}
}
}
Generic null ref exception question. You didn't indicate the line throwing the exception. A null ref exception always means you tried to use a variable that was never assigned to, or the object it represents got nullified. Figure out which variable is null, and do null-checks if anywhere a variable might ever be null.
if ( myVariable == null ) DoSomething(); else DoSomethingElse();
oops, i diddn't relize i left that blank, sorry. line 19
You declared GameObject player as public but probably haven't dragged your player object into that field in the Inspector.