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