can someone help me with my targeting script?

Hey guys, so I got a basic targeting script, wich by itself is fine. The only thing is, when I destroy an object in game (aka kill an enemy) it messes the hole script up, and makes all of its refrences screwy. Could someone help me? I want to recall my eneycount code or simply let the number go down as it goes but have no idea how to set it up. Here’s my tartgeting script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class targeting : MonoBehaviour {

public List<Transform> targets;
private Transform selectedtarget;

private Transform mytransform;

// Use this for initialization
void Start () {
	targets = new List<Transform>();
	selectedtarget = null;
	mytransform = transform;
	
	addallenemys();

}

public void addallenemys()
{
	GameObject[] go = GameObject.FindGameObjectsWithTag("enemy");
	
	foreach(GameObject enemy in go)
		AddTarget(enemy.transform);
}

public void AddTarget(Transform enemy)
{
	targets.Add(enemy);
}

private void sorttargetsbydistance()
{
	targets.Sort(delegate(Transform t1, Transform t2) { 
		return Vector3.Distance(t1.position, mytransform.position).CompareTo(Vector3.Distance(t2.position, mytransform.position));
		                        });
}

private void targetenemy()
{
			if(selectedtarget == null)
			{
				sorttargetsbydistance();
		selectedtarget = targets[0];
			}
	else{
		int index = targets.IndexOf(selectedtarget);
		if(index < targets.Count - 1)
		{
			index++;
		}
		else
		{
			index = 0;	
		}
		deselecttarget();
		selectedtarget = targets[index];
		
	}
	selecttarget();
	
}


	


private void selecttarget()
{
	selectedtarget.renderer.material.color = Color.cyan;
	
	basicpattack pa = (basicpattack)GetComponent("basicpattack");
	
	pa.target = selectedtarget.gameObject;
}

public void deselecttarget()
	{
	selectedtarget.renderer.material.color = Color.red;
	selectedtarget = null;
}


// Update is called once per frame
void Update () {
	if(Input.GetKeyDown(KeyCode.Tab))
	{
		targetenemy();
	}
if(selecttarget = null)
	
		
	
	}
}

Thanks for the help

When you are destroying the enemy via script, you would need to remove the reference in the list of targets in your targeting script as well. You should do this right before you destroy the game object in question.

public void DestroyTarget(Transform target)
{
   targets.Remove(target);
   GameObject.Destroy(target.gameObject);
}

You could also leave out the Destroy in this function and call it from somewhere else if you like, but I tend to prefer to have things grouped like this when I’m cleaning up an object.