纳金网

标题: 根据物体离目标点的距离进行排序 [打印本页]

作者: 烟雨    时间: 2015-8-28 01:13
标题: 根据物体离目标点的距离进行排序
实现这种功能有很多种,下面是我个人认为比较好的实现方法
  1. /*

  2. * @ 创建时间:2015.8.12.8:59

  3. * @ 作者           杉树

  4. * @ 修改人:

  5. * @ 修改时间:

  6. * @ 描述:根据物体离,目标点的距离排序

  7. *

  8. */

  9. using UnityEngine;
  10. using System.Collections;
  11. using System.Collections.Generic;


  12. public class Sort : MonoBehaviour {

  13.     public List<Transform> list;
  14.         // Use this for initialization
  15.         void Start () {
  16.         list = new List<Transform>();

  17.         AddAllCubes();
  18.        
  19.         }
  20.        
  21.         // Update is called once per frame
  22.         void Update () {
  23.        
  24.         }
  25.     void OnGUI()
  26.     {
  27.         DisplaySortOnGUI();
  28.         if (GUILayout.Button("SortObjsByDistance"))
  29.         {
  30.             SortObjsByDistance();
  31.         }
  32.     }

  33.     void AddAllCubes()
  34.     {
  35.         GameObject[] go = GameObject.FindGameObjectsWithTag("cube");
  36.         foreach(GameObject cube in go)
  37.         {
  38.             list.Add(cube.transform);
  39.         }
  40.     }
  41.     void SortObjsByDistance()
  42.     {
  43.         list.Sort(delegate(Transform t1,Transform t2)
  44.         {
  45.             Debug.Log(Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position)));
  46.             return Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position));
  47.         });
  48.     }

  49.     void DisplaySortOnGUI()
  50.     {
  51.         foreach (Transform t in list)
  52.         {
  53.             GUILayout.Label(t.name);
  54.         }
  55.     }

  56. }
复制代码





欢迎光临 纳金网 (http://wwww.narkii.com/club/) Powered by Discuz! X2.5