在之前的文章我讲解过了数据结构:树,二叉树等的基础知识与实现方式,对于树结构不懂的可以查看 二叉树基础(上):什么样的二叉树适合用数组来存储?
今天我们来通过树实现游戏中的红点系统。
Damo地址:红点树
红点系统需要具备哪些能力?
- 支持多层级树结构,支持显示数量
- 可动态注册节点事件或撤销节点事件
- 需要显示红点的UI会注册一个节点的Key,可以是叶子结点也可以是非叶子结点。
- 当子节点的红点发生变化,向上递归的通知父节点发生改变。
- 使用红点系统的人只需要策划配置的红点key,与红点的具体数量,不需要关系其他节点与该节点的联系。
我将功能拆分成3个类
RedDotSystem:用来控制和刷新树的改变,消息监听和注册
RedDotNode: 红点树的结构
RedDotCompoent:红点组件,根据RedDotNode数据控制UI显示隐藏
RedDotSystem 核心的代码:
public void SetRedDotCount(string key,int num)
{
CheckInit();
if (!redDotDic.TryGetValue(key, out RedDotNode node))
{
Debug.LogError("not find RedDotNode Key:" + key);
return;
}
if (node.HasChildren())
{
Debug.LogError("该节点是根节点,无法直接改变数值,通过修改子节点的数量改变");
return;
}
node.SetCount(num);
// 通知父物体
RedDotNode parent = node.parent;
while (parent != null)
{
Debug.Log("parent key : "+parent.Key);
int parentNum = 0;
for (int i = 0; i < parent.childrens.Length; i++)
{
parentNum += parent.childrens[i].Count;
}
parent.SetCount(parentNum);
parent = parent.parent;
}
}
时间复杂度:O(h) h为数的高度