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
	private void OnTriggerStay2D(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.

In the attack() function… try to create an if statement like the one in the trigger function

I suppose the attack function isnt finding the “target” because the turrent hasent yet come into contanct with the enemy, therefor not assuming an enemy to the “target” variable ^_^!

if you create the if statement if the attack function… it will only attack the “target” variable, if it has and object attached to it :D!