Multiple objects with the same script having trouble accessing another script/object

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.

your tower colliders are maybe colliding. you need to make sure its an enemy before you continue. your tower parent is probably null which is causing an exception trying to get nothings gameobject.

I wrote this a while back, which is another way to look at handling target tracking. In general I would avoid OnTriggerStay, its pretty expensive in terms of performance.