IComparable IComparer 比較器實例與使用

概述:

IComparable 表示類能夠去比較。
IComparer 是比較器,能夠去比較兩個實例的大小。
雞蛋和雞蛋間本身無法比較哪個重,電子稱可以分辨兩個雞蛋(或其他物體)誰更重,所以 電子稱可以看作是IComparer
人可以通過掰手腕,比出那個人力氣大,所以人可以看作是IComparable 可以相互間比較的。

比較器實例:

 

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

public class UnrealDistanceComparer:Comparer<GameObject>
{
	private Vector3 _zeroPoint = Vector3.zero;
	//首先保存距離,若存在則取,否則重新計算
	private Dictionary<GameObject,float> dic_GoToZeroDistance = new Dictionary<GameObject, float> ();

	public UnrealDistanceComparer (Vector3 zeroPoint)
	{
		this._zeroPoint = zeroPoint;
	}

	public override int Compare (GameObject go1, GameObject go2)
	{
		if (go1 == null && go2 == null) {
			return 0;
		}
		if (go1 == null) {
			return -1;
		}
		if (go2 == null) {
			return 1;
		}
		float distance1;
		float distance2;

		if (dic_GoToZeroDistance.ContainsKey (go1)) {
			distance1 = dic_GoToZeroDistance [go1];
		} else {
			distance1 = Vector3.Distance (go1.transform.position, _zeroPoint);
		}
		if (dic_GoToZeroDistance.ContainsKey (go2)) {
			distance2 = dic_GoToZeroDistance [go2];
		} else {
			distance2 = Vector3.Distance (go2.transform.position, _zeroPoint);
		}

		if (distance1 < distance2) {
			return -1;
		}

		if (distance1 > distance2) {
			return 1;
		}
		return 0;
	}
}

 

使用方法:allEnemies是一個list類型

 

allEnemies.Sort (new UnrealDistanceComparer (transform.position));

 

使用前

 

使用後

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章