Unity3D学习笔记——选择Enemy

时间:2024-01-08 20:46:44

  一、步骤:

    1、创建三个Cube,并将这三个Cube的Cube的Tag设为Enemy

    2、导入第一人称视角的资源

    3、创建名为Targeting的C#脚本

    4、编写Targeting脚本,并将它附到第一人称的对象上

  二、Targeting脚本

    

using UnityEngine;
using System.Collections;
using System.Collection.Generic; public class Targetting:MonoBehaviour{
public List<Transform> targets;
public Transform selectTarget; void Start(){
targets=new List<Transform>();
selectTarget=null;
addAllElements();
targetEnemy();
} void Update(){
if(GetKeyDown(KeyCode.Tab)){
targetEnemy();
}
} public void addAllElements(){
GameObject[] go=GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go){
addTarget(enemy.transform);
}
} private void addTarget(Transform enemy){
targets.Add(enemy);
} private void sortTargetByDistance(){
targets.Sort(delegate(Transform t1,Transform t2){
return Vector3.Distance(t1.position,transform.position).ComparaTo(Vector3.Distance(t2.position,transform.position));
});
} public void targetEnemy(){
if(SelectTarget==null){
sortTargetByDistance();
selectTarget=targets[];
}
else{
int index=targets.IndexOf(selectTarget) ;
if(index<targets.Count-){
index++;
}
else{
index=;
}
DeSelectTarget();
selectTarget=targets[index];
}
SeleteTarget();
} private void SelectTarget(){
selectTarget.renderer.material.color = Color.green;
} private void DeSelectTarget(){
selectTarget.renderer.material.color = Color.red;
selectTarget = null;
}
}

  三、实验结果

    Unity3D学习笔记——选择EnemyUnity3D学习笔记——选择Enemy