2d AI: enemy targeting c#

Hi

I’m developing a 2d game where I spawn ally units from left to right. I’m trying to get my enemy units to fire a projectile at the ally units once they come within range on the x axis. My script works fine if I have an ally unit already placed in the scene but if I start the scene without a pre-spawned ally there is an error that says: UnassignedReferenceException: The variable target of ‘Enemy’ has not been assigned.
Here is my enemy script:

void Start () {

  GameObject go = GameObject.FindGameObjectWithTag("AllyTag");
	
  target = go.transform;
	
	
  SetPositionAndSpeed();
}

// Update is called once per frame
void Update () {

	float amountToMove = currentSpeed * Time.deltaTime; 
	transform.Translate(Vector3.left * amountToMove);
	
	
	StopAndShoot();//if target comes within range
	
	 
	 
}




public void SetPositionAndSpeed(){
	
	//getting speed
currentSpeed = Random.Range(MinSpeed, MaxSpeed);
	
	
}


void StopAndShoot(){
	x = transform.position.x;
	c = target.position.x;
	
	if(c>=x-6){
		
		currentSpeed = 0;//stop
		Instantiate (BulletPrefab,transform.position,Quaternion.Identity);//fire bullet

                }
 
 }

}

If anyone can help it would be great.
Regards
Vinny

2 Answers

2

If there is no object int the game scene with “allytag” tag, then the Find will return a NULL. Put an if statement checking fora NULL first. If it is not Null then do ur thing.

Also when u spawn an enemy, check its name in the haeirarchy, it could have a (Clone) attached behind its name. You can check for the name as well and assign it a new name when it is spawned.

Thanks for the advice guys. I have it working now using the co-routine method.