Looking at closest visible object with tag
Hello, Previously I had a script that I could look at a player but only when I had the Tab buttoned pressed down but could not cycle through enemies or anything. Looking all day for answers I came by this and decided it would be great I can now find things tagged enemies and cycle though them but I have not been able to figure out a way to lookat the enemy and stay looking at them and be able to move around them in a circle.
public class debug : MonoBehaviour
{
public List<Transform> targets;
public Transform selectedTarget;
public string targetTag = "Enemy";
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(targetTag);
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 SortTargetsByDistance()
{
targets.RemoveAll(target => target == null);
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();
}
}
}
Your answer
Follow this Question
Related Questions
How can I make a third person camera collision script? 2 Answers
What is wrong with the code I have written for the camera to avoid it from going through object 1 Answer
Rotated object raycasting in wrong directions!!? 3 Answers
Instantiating object in the wrong place,Instantiate object at mouse point getting wrong coordinates 1 Answer