I have a character that (in theory) goes to an enemy when I point at it. Currently, I’m using a raycast that checks if the thing is an enemy and then saves it as an object in the pointer script on the player
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, out hit, 40))
{
WhipEnemy we = hit.transform.GetComponent<WhipEnemy>();
if (we != null)
{
Target = hit.transform.gameObject;
attacking = true;
}
}
then the character script references that and should pathfind to it
You did not show the full code but presumably Target is not always set. For example, before you give it its first value. Your character controller has a null check for Target, but above that you still use ns.Target.transform.position in your SetDestination call. So if Target is null, then that line will trigger a NullReferenceException. You probably want to move it into your null check. If that does not do what you want it to do you might want to provide more context and/or code.
Classical mistake. In this line you SET ns.Target to null. You did not check it against null. Comparison is done with ==. A single = means assignment.
Apart from that in the line before you already try to access the transform of the Target. When the target is actually null that line would throw a null reference exception. So it should be inside the null checked if body.