Hey guys,
I’m working on a project, and right now I am trying to get the “tab” key to cycle through my enemies, however I can’t get it to fill my list with my tagged targets. Can someone please take a look at my code, and tell me why the list won’t populate at game start? I think there is something going wrong in my AddAllEnemies() Method, but I can’t for the life of my figure out what it is. Thanks so much in advance guys…any help would be greatly appreciated. (And just FYI…I have tired the script to my player). lol
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
public List targets;
public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start () {
targets = new List();
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];
}
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Tab))
{
TargetEnemy();
}
}
}