List problem missing object

I got a turret defence game and i got a script on the tower that controls it and it get the enemies within the range and put them in a list i want to now if theres any way to erase the enemies after the turret kills it because i remove it and it works but the list keeps getting larger and it storage missing values is there any way to filter the list or purge it?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TorretaAI : MonoBehaviour {

	public Transform BaseTorreta;
	public Transform Enemigo;
	public List<Transform> Enemigos = new List<Transform>();
	public float RotationSpeed = 1;
	public Rigidbody bulletPrefab;
	public Transform bulletSpawn;
	public float AttackSpeed;
	public float shotInterval = 0.5f;
	public float bulletSpeed = 500f;
	public float counter;
	public bool Timer = true;
	public float tiempo;
	public int Daño;
	private VidaEnemigo eh;

	// Use this for initialization
	void Start () {
		counter += Time.deltaTime;

	}

	void OnTriggerStay (Collider other){
		if (other.tag == "enemigo") {
			if (!Enemigos.Contains(other.transform)){
				Enemigos.Add(other.transform);
			}
			
		}
	}



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

		Enemigos.Sort(delegate(Transform t1, Transform t2){return Vector3.Distance(t1.position, BaseTorreta.position).CompareTo(Vector3.Distance(t2.position, BaseTorreta.position));});   

		if (Enemigos.Count > 0){
			Enemigo = Enemigos [0];
		}
						


		if (Enemigo)
		{
			eh = Enemigo.gameObject.GetComponent<VidaEnemigo>();
			BaseTorreta.rotation = Quaternion.Slerp(BaseTorreta.rotation, Quaternion.LookRotation(Enemigo.transform.position - BaseTorreta.position), Time.deltaTime * RotationSpeed);
			if (Time.time >= AttackSpeed)
			{
				Rigidbody bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) as Rigidbody;
				bullet.rigidbody.AddForce(transform.forward * bulletSpeed);
				AttackSpeed = Time.time + shotInterval;
				if (counter >= tiempo)
				{
					
					eh.AddjustCurrentHealth(-Daño);
					counter = 0;
				}
			}
			if (eh.curHealth <= 0){
				
				Enemigo = null;
				Enemigos.RemoveAt(0);
			}
		}
	}

	void OnTriggerExit (Collider other){
		if (other.tag == "enemigo") {
			if (Enemigos.Contains(other.transform)){
				Enemigos.Remove(other.transform);
			}

		}
	}
}

1 Answer

1

Try this

The other option is to use OnDestroy in the objects being removed from the list.

that works but just in one turret, any idea?

I assume you have the same script attached to each turret? Why does it only work for one?

yes i have it in every turret, dont now why, perhaps its because it only call the function once dont now?