I want to destroy the first spawned gameobject once x amount of gameobjects are spawned. So lets say I shoot projectiles. Then I want to despawn or destroy the first projectile I shot (which will be the one the most far away) once I’ve shot lets say 5 projectiles. So there can’t be more than 5 projectiles in the air.
How do I go about doing this? I tried the FindGameObjectsWithTag.Length method to count the amount of projectiles, but then I dont know how to destroy the one I shot first from the 5.
On the player I have the playerController script. This spawns the gameobjects or projectiles once I hit the spacebar.
public GameObject Projectile;
void Update()
{if (Input.GetKeyDown(KeyCode.Space))
{
//spawn projectile
Instantiate(Projectile, transform.position, Projectile.transform.rotation);
}
This works to shoot the projectiles. And then on the projectile itself I have the ProjectileDestroy script:
I gave the projectile a tag. “Projectiletag”.
public int Projectiles;
// Start is called before the first frame update
void Start()
{
GameObject.FindGameObjectsWithTag("Projectiletag").Length;
}
void Update()
{
if (GameObject.FindGameObjectsWithTag("Projectiletag").Length== 5)
{
Destroy(gameObject);
}
This code destroys all projectiles once 5 are reached. Not the one I shot first. Any help is appreciated.