根据与目标距离排序

实现这种功能有很多种,下面是我个人认为比较好的实现方法

[code]phpcode:

/*

* @ 创建时间:2015.8.12.8:59

* @ 作者           杉树

* @ 修改人:

* @ 修改时间:

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

* 

*/

using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class Sort : MonoBehaviour {

    public List list;
	// Use this for initialization
	void Start () {
        list = new List();

        AddAllCubes();
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void OnGUI()
    {
        DisplaySortOnGUI();
        if (GUILayout.Button("SortObjsByDistance"))
        {
            SortObjsByDistance();
        }
    }

    void AddAllCubes()
    {
        GameObject[] go = GameObject.FindGameObjectsWithTag("cube");
        foreach(GameObject cube in go)
        {
            list.Add(cube.transform);
        }
    }
    void SortObjsByDistance()
    {
        list.Sort(delegate(Transform t1,Transform t2)
        {
            Debug.Log(Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position)));
            return Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position));
        });
    }

    void DisplaySortOnGUI()
    {
        foreach (Transform t in list)
        {
            GUILayout.Label(t.name);
        }
    }

}

你可能感兴趣的:(根据与目标距离排序)