# (unity3d) Raycast Tags: Object reference not set to an instance of an object not working!

Here is the code I have written for an AI:

public Transform player;
public NavMeshAgent Enemy;
public CharacterPowers CharPow;
public GameObject me;

// Update is called once per frame
void Update () {
Vector3 targetDir = player.position - transform.position;
float angleToPlayer = (Vector3.Angle(targetDir, transform.forward));

if (angleToPlayer >= -90 && angleToPlayer <= 90)
{
RaycastHit hit;
Physics.Raycast(me.transform.position, player.position, out hit);

if(hit.transform.tag == "MainChar")
{

if(CharPow.IsCloaked == false)
{
Debug.Log("Player in sight!");
Enemy.destination = player.position;
}

}

}

}


However, according to the error message, the line

if(hit.transform.tag == "MainChar")

is missing a reference to an object. I have checked, and yes, the player character does have the tag. Everything else used to work, such as the cloaking mechanic. However, now nothing about the AI works at all.

Raycasting methods take a start point and a direction, but you're passing two points: a start and an end. The second point will not be interpreted the way you expect.

player.position - me.transform.position


to get a vector pointing toward the player from the start point at "me".

You should still check whether you've hit anything at all before you try to access the members of the resulting RaycastHit, so you don't hit NullReferenceExceptions even when unusual situations arise (like me being inside the player's collider)

You'll also want to use the CompareTag method instead of .tag == for efficiency.

• Note: To check whether the raycast hit something, Physics.Raycast returns a bool, so just use if (Physics.Raycast...) {...} where the rest of your code is inside the body of the if – Ed Marty Jul 4 '18 at 13:52

I think that instead of if(hit.transform.tag == "MainChar") you should use if(hit.gameObject.tag == "MacinChar"). Did you try this?

• Yes. It does not work. – Spaceguy99 Jul 3 '18 at 23:33
• Try to put some Debug.Log(hit.transform.tag); after Physics.Raycast(...) and see what tag you'll get – Seweryn Pokutycki Jul 3 '18 at 23:35
• it returns the same error request as usual – Spaceguy99 Jul 3 '18 at 23:38