Alright, so firstly I’ll apologize if I’m not doing this right, but I’m new here…
I’m working on a targetting script for a learning project and have hit a bit of a roadblock I hoped someone with a bit of experience could help me sort. Basically I’m trying to add in functionality of selecting a new target when the specified key is pressed but there are a couple of conditions.
- If there is a new target closer than the old target it takes priority.
- If there are several targets should cycle through the list of targets with each keypress.
I have the basic functionality in place (though it may not be the best approach) and it sorts by distance and refreshes with the nearest target, I’m just stumped on the rest. I’m open to any suggestions or improvements, but mostly just want a nudge in the right direction. The code is below:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targetting : MonoBehaviour {
private Transform myTransform;
public List<Transform> targets;
public Transform selectedTarget;
public Transform previousTarget;
// Use this for initialization
void Start () {
myTransform = transform;
selectedTarget = null;
targets = new List<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);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Tab))
TargetEnemy ();
}
private void TargetEnemy () {
SortTargetsByDistance ();
if (selectedTarget == null) {
selectedTarget = targets[0];
SelectTarget ();
}
else {
previousTarget = selectedTarget;
DeselectTarget ();
TargetEnemy ();
}
}
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 SelectTarget () {
selectedTarget.renderer.material.color = Color.red;
}
private void DeselectTarget () {
previousTarget.renderer.material.color = Color.blue;
selectedTarget = null;
}
}
Thanks in advance for any assistance.