I am working on a simple tower defense game. At the moment I have one tower and multiple enemy objects and everything works fine (enemy within circle collider, attack and destroy enemy).
However, when I add a second tower (identical prefab, same script), I get the following error for both towers when trying to attack:
NullReferenceException: Object reference not set to an instance of an object
This is confusing to me because with one tower it can access the enemy fine, but simply dragging and dropping another tower breaks this.
Here I get the enemy that has entered the towers radius:
GameObject target;
// Checks if any enemies are within the turrets range radius
privatevoidOnTriggerStay2D(Collider2D other){
if(target ==null){
target = other.transform.parent.gameObject;
}
}
And here the turret attacks the enemy:
private void attack(){
target.GetComponent<EnemyBehavior>().receiveDamage(damage);
}
Any idea on what the issue is? I am fairly new to Unity so I’m not sure what the best approach is to accessing other scripts. It seems like my two towers with the same script are conflicting somehow? I’d appreciate any help.