选择一个敌人,按ctrl+d,复制出3个,调整一下它们的位置,不重叠,修改Tag为Enemy,禁用EnemyAI。
创建Targetting脚本,绑定到Player玩家对象
public class Targetting : MonoBehaviour { public List<Transform> targets; public Transform selectedTarget; // Use this for initialization void Start () { targets = new List<Transform> (); AddAllEnemies (); } public void AddAllEnemies(){ GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy"); foreach (GameObject enemy in go) { targets.Add(enemy.transform); } } public void SelectTarget(){ selectedTarget = targets [0]; } // Update is called once per frame void Update () { if (Input.GetKeyUp (KeyCode.Tab)) { SelectTarget (); } } }
运行查看属性如下
当按Tab时,第一个敌人被获取到SelectedTarget中
下面完善Tab键选敌人功能:
1. 假如已选敌人为null,那么选择最近敌人,并将已选敌人的材质的颜色改为红色。
2. 假如已选敌人不为null,那么按Tab将选择当前已选的下一个敌人(按距离排序),将之前选的敌人颜色改成绿色,新选的改成红色。
3. 在选择敌人完成后,调用Player的PlayerAttack组件,给它的target赋值。完整如下:
public class Targetting : MonoBehaviour { public List<Transform> targets; public Transform selectedTarget; public Transform myTransform; // Use this for initialization void Start () { targets = new List<Transform> (); AddAllEnemies (); myTransform = transform; } public void AddAllEnemies(){ GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy"); foreach (GameObject enemy in go) { targets.Add(enemy.transform); } } //按距离排序敌人 public void SortTargetByDistance(){ targets.Sort (delegate(Transform t1, Transform t2){ return Vector3.Distance(t1.position,myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position)); }); } //选择敌人 public void SelectEnemy(){ if (selectedTarget == null) { SortTargetByDistance (); selectedTarget = targets [0]; } else { int index = targets.IndexOf(selectedTarget); if(index < targets.Count - 1){ index++; }else{ index = 0; }
//删除之前选择的敌人 DeleteTarget(); selectedTarget = targets[index]; }
//已选择敌人 SelectTarget(); } private void SelectTarget(){ selectedTarget.renderer.material.color = Color.red;
//给攻击组件赋值,切换当前攻击的敌人 PlayerAttack pa = (PlayerAttack)GetComponent ("PlayerAttack"); pa.target = selectedTarget.gameObject; } private void DeleteTarget(){ selectedTarget.renderer.material.color = Color.blue; } // Update is called once per frame void Update () { if (Input.GetKeyUp (KeyCode.Tab)) { SelectEnemy (); } } }