Hello, for some reason it appears that findgameobjectwithtag does not work sometimes. I receive this error only sometimes:
NullReferenceException: Object reference not set to an instance of an object
Unity says the error is at line 5
Heres the code :
targets = GameObject.FindGameObjectsWithTag("Good"); //stores all viable targets
for (int i = 0; i < targets.Length; i++) { //goes through targets
GameObject target = targets *;*
-
if(target != null) {*
-
if(Physics2D.Raycast(transform.position + new Vector3(0, 0.6f, 0), target.transform.position - transform.position, range).collider.name == target.name) {*
-
Debug.DrawRay(transform.position + new Vector3(0, 0.6f, 0), target.transform.position - transform.position);*
-
float weight = Vector3.Distance (target.transform.position, transform.position);*
-
if (weight > highestWeight) { //chooses closest/most important target*
-
highestWeight = weight;*
-
bestMatch = target;*
-
lastTargetSeen = target;*
-
}*
-
}*
-
}*
-
}*