using UnityEngine; using System.Collections.Generic; namespace YKMoon { /// /// ID生成器,可以生成一定个数的唯一ID,用来做循环可回收的ID用 /// public class IDGenerator { const int DEFAULT_MAX = 10000; public IDGenerator(int max = DEFAULT_MAX) { idMax = max; } private HashSet idList = new HashSet(); private int idIndex = 0; private int idMax = DEFAULT_MAX; /// /// 生成ID /// public int GetNextUIId() { if (idList.Count >= idMax) { Debug.LogError("IDGenerator:too many ID, it must be an error!!"); return -1; } int whileCount = 0; do { idIndex = (idIndex + 1) % idMax; whileCount += 1; if (whileCount >= idMax) { Debug.LogError("IDGenerator:too many ID, it must be an error!!"); return -1; } } while (idList.Contains(idIndex)); idList.Add(idIndex); return idIndex; } /// /// 回收ID /// /// public void RemoveId(int id) { if (idList.Contains(id)) { idList.Remove(id); } } public int GetCount() { return idList.Count; } public void Clear() { idIndex = 0; idList.Clear(); } } }