Unity3D学习笔记——选择Enemy

  一、步骤:

    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[0];
    }
    else{
      int index=targets.IndexOf(selectTarget)   ;
      if(index<targets.Count-1){
        index++;
      }
      else{
        index=0;
      }
       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;
  }
} 

  三、实验结果

    

posted @ 2013-11-02 13:41  LOSER Z  阅读(423)  评论(0编辑  收藏  举报