- Home /
NullReferenceException when an object is in the way that is not the player
so I had my enemy script working to detect my player tag but what i didn't account for was if another object/ object tag was detected. it throws me a NullReferenceException : UnityEngine.Component.get_gameObject ()...... and no matter how many forum posts i read, i could not find a solution :(.
here is the script:
void enMoveLeft ()
{
rigidbody.velocity = new Vector3(-moveSpeed,0.0f,0.0f);
//checks against farthest left point of the character to the farthest left
//point of the platform to make the enemy turn around
if(leftSide <= platLeft)
{
print ("going over the left edge!!!");
pos = platLeft + ((-platLeft + platRight)/2);
//print (pos + " = pos");
turn = true;
}
//moves the player 10.0f to the left
if(Physics.Raycast(transform.position, -Vector3.right, out hit, distance))
{
//if player spotted, chase
if(hit.rigidbody.gameObject.tag == "Player")
{
//print ("I see you!!!");
rigidbody.velocity = new Vector3(-moveSpeed*chaseSpeed,0.0f,0.0f);
pos = rigidbody.position.x;
}
}
else
{
if(rigidbody.position.x <= (pos - 10.0f))
{
transform.localScale = new Vector3((this.transform.localScale.x*-1), this.transform.localScale.y, this.transform.localScale.z);
turn = true;
}
}
}
and it throws me the error on this line:
if(Physics.Raycast(transform.position, -Vector3.right, out hit, distance))
any help would be greatly eppreciated
Answer by gregzo · Jul 27, 2013 at 01:29 PM
if ( Physics.Raycast(transform.position, -Vector3.right, out hit, distance))
{ //first make sure a collider was hit, then check the tag.
if ( hit.collider != null && hit.collider.tag == "Player" ) //Not all colliders have rigidbodies, and tag can be accessed directly through a collider.
{
Debug.Log ( "player was hit!" );
}
}
darn it all........ that was the first thing i tried and it was all like im not ganna do it, now it works hahaha thanks for the answer
Your answer
![](https://koobas.hobune.stream/wayback/20220613111007im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
AI raycasting problem 0 Answers
Object reference not set to an instance of an object 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Picking Weapons Up with Raycast 1 Answer