I use 2 scripts which help me target an enemy when I press tab. And when that enemy is targeted I can only damage that enemy however when I kill one enemy it has a missing game object, I understand the issue. I’m just unaware of how to fix it and would appreciate someone to help.
BASE TARGETTING SCRIPT:
public class Targetting : MonoBehaviour
{
public List targets;
public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start()
{
targets = new List<Transform>();
selectedTarget = null;
{
myTransform = transform;
AddAllEnemies();
}
}
public void AddAllEnemies()
{
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;
}
selectedTarget = targets[index];
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
TargetEnemy();
}
}
PLAYER ATTACK SCRIPT:
public class PlayerAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float coolDown;
public Targetting TargetSystem;
// Use this for initialization
void Start () {
attackTimer = 0;
coolDown = 1.0f;
TargetSystem = GetComponent<Targetting>();
}
// Update is called once per frame
void Update()
{
target = TargetSystem.selectedTarget.gameObject;
if (attackTimer > 0)
attackTimer -= Time.deltaTime;
if (attackTimer < 0)
attackTimer = 0;
if (Input.GetKeyUp(KeyCode.F))
{
if(attackTimer == 0)
Attack();
attackTimer = coolDown;
}
}
private void Attack()
{
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
Debug.Log(direction);
{
}
Debug.Log(distance);
if (distance < 4)
{
if (direction > 0)
{
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustCurrentHealth(-10);
}
}
}
}