how to limit amount of objects instantiated?

Hi, i have a code that instatiates my Enemy Fighetrs. Cool :smiley: but it loops and loops and loops. :smiley:
need a way to make it so it spawns 5 fighters maximum , then when a fighter is destroyed it replaces it.
how dose one go about doing this? if(CurrentFighters < 3) dose not do anything an dis not helpful. :smiley:

using UnityEngine;
using System.Collections;

public class Carrier : Photon.MonoBehaviour {

	public int CurrentFighters = 0;
	public int CarrierHealth = 2000;
	public GameObject Fighter;
	
	// Update is called once per frame
	void Update () {
		// set here maximum fighters at any one time.
			Rigidbody clone;
			clone = (Rigidbody)Instantiate(Fighter, transform.position, transform.rotation);
			CurrentFighters += +1;
	}

		if(CarrierHealth <1){
			CarrierDestroyed ();
		}
} // End Update


	void CarrierDestroyed ()	{
		Destroy (this.gameObject);
	} //End Destroyed

} // End Class

1 Answer

1

void Update (){

if(CarrierHealth <1)
CarrierDestroyed ();

if (CurrentFighters > 4)
return;

Rigidbody clone;
clone = (Rigidbody)Instantiate(Fighter, transform.position, transform.rotation);
CurrentFighters += +1;
}