Unity 树形结构 动态加载Tree

   提示:源码附在文后~大家互相学习

目录

前言

一、组件结构

1. Tree预制体结构

2. 项目结构

二、功能实现

1.初始化树结构      

2.ItemPrefab加载

3.新增ItemPrefab

4.修改ItemPrefab

5.删除temPrefab

总结



前言

管理系统中,时常有树形结构管理需求。使用频率较高。本文章对树形结构拼接做到基础功能实现。可以满足一般树形结构操作需求。所以整理出组件,方便每次使用!大家共同学习!


一、组件结构

 1. Tree预制体结构

2. 项目结构

二、功能实现

1.初始化树结构      

  • 将TreeManager脚本绑定至Tree预制体上,用于整体控制树型结构初始化及基本操作方法绑定。

  • 脚本Start方法用作初始化数据,目前为假数据拼接。注释掉部分可从后台数据库读取,动态拼接树形结构。
void Start()
        {
           

            ResManager rm = ResManager.Instance;
            mTreeView.OnTreeListAddOneItem = OnTreeListAddOneItem;
            mTreeView.OnTreeListDeleteOneItem = OnTreeListDeleteOneItem;
            mTreeView.OnItemExpandBegin = OnItemExpandBegin;
            mTreeView.OnItemCollapseBegin = OnItemCollapseBegin;
            mTreeView.OnItemCustomEvent = OnItemCustomEvent;
            mTreeView.InitView();


            ******************假数据动态拼接树开始****************************
            TreeViewItem item1 = mTreeView.AppendItem("ItemPrefab1");
            item1.GetComponent<ItemScript>().SetItemInfo("全部", "全部", "1");


            TreeViewItem childItem1_1 = item1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_1.GetComponent<ItemScript>().SetItemInfo("技术部门", "技术部门", "1_1");
            TreeViewItem childItem1_2 = item1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_2.GetComponent<ItemScript>().SetItemInfo("商务部门", "商务部门", "1_2");
            TreeViewItem childItem1_3 = item1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_3.GetComponent<ItemScript>().SetItemInfo("行政部门", "行政部门", "1_3");
            TreeViewItem childItem1_4 = item1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_4.GetComponent<ItemScript>().SetItemInfo("总裁办", "总裁办", "1_4");



            TreeViewItem childItem1_1_1 = childItem1_1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_1_1.GetComponent<ItemScript>().SetItemInfo("技术一部", "技术一部", "1_1_1");
            TreeViewItem childItem1_1_2 = childItem1_1.ChildTree.AppendItem("ItemPrefab1");
            childItem1_1_2.GetComponent<ItemScript>().SetItemInfo("技术二部", "技术二部", "1_1_2");

           
            ******************假数据动态拼接树结束****************************

            ******************后台数据动态拼接树开始****************************
            //    outlineInfoList = ServiceManager.Instance().GetAllTree();
            //    allTreeViewItemList = new List<TreeViewItem>();
            //    TreeViewItem item1 = new TreeViewItem();
            //    for (int i = 0; i < outlineInfoList.Count; i++)
            //    {
            //        if (string.IsNullOrEmpty(outlineInfoList[i].ParentId) || int.Parse(outlineInfoList[i].ParentId) == 0)
            //        {
            //            item1 = mTreeView.AppendItem("ItemPrefab1");
            //            item1.GetComponent<ItemScript>().id = outlineInfoList[i].OutlineId;
            //            item1.GetComponent<ItemScript>().parentId = outlineInfoList[i].ParentId;
            //            item1.GetComponent<ItemScript>().labelText.text = outlineInfoList[i].OutlineName;
            //            item1.GetComponent<ItemScript>().SetItem(item1.GetComponent<ItemScript>());
            //            allTreeViewItemList.Add(item1);
            //        }
            //        else
            //        {
            //            for (int j = 0; j < allTreeViewItemList.Count; j++)
            //            {
            //                if (allTreeViewItemList[j].GetComponent<ItemScript>().id.Equals(outlineInfoList[i].ParentId))
            //                {
            //                    TreeViewItem childItem = allTreeViewItemList[j].ChildTree.AppendItem("ItemPrefab1");
            //                    childItem.GetComponent<ItemScript>().id = outlineInfoList[i].OutlineId;
            //                    childItem.GetComponent<ItemScript>().parentId = outlineInfoList[i].ParentId;
            //                    childItem.GetComponent<ItemScript>().labelText.text = outlineInfoList[i].OutlineName;
            //                    childItem.GetComponent<ItemScript>().SetItem(childItem.GetComponent<ItemScript>());
            //                    allTreeViewItemList.Add(childItem);
            //                }
            //            }
            //        }
            //    }
            //    OnItemCustomEvent(item1, CustomEvent.ItemClicked, "");
            ******************后台数据动态拼接树结束****************************
        }
  • 注释:后台数据库设计如图所示,Level字段为当前层级id及其所有父层及id用逗号拼接的字符串格式。

2.ItemPrefab加载

  • TreeView上绑定 TreeView脚本,用于初始化管理ItemPrefab事件绑定。

 //called when a item is added to a TreeList
        public Action<TreeList> OnTreeListAddOneItem;
        //called when a item is deleted to a TreeList
        public Action<TreeList> OnTreeListDeleteOneItem;
        //called when a item is begin to expand its chlidtree.
        public Action<TreeViewItem> OnItemExpandBegin;
        //called when a item is expanding its chlidtree.
        public Action<TreeViewItem> OnItemExpanding;
        //called when a item has expanded its chlidtree.
        public Action<TreeViewItem> OnItemExpandEnd;
        //called when a item is begin to collapse its chlidtree.
        public Action<TreeViewItem> OnItemCollapseBegin;
        //called when a item is collapsing its chlidtree.
        public Action<TreeViewItem> OnItemCollapsing;
        //called when a item has collapsed its chlidtree.
        public Action<TreeViewItem> OnItemCollapseEnd;
        //called when a custom event is raised. you can raise a custom event by 
        //call TreeViewItem:RaiseCustomEvent(CustomEvent customEvent,System.Object param)
        //to notify the TreeView something happens, such as a TreeViewItem is clicked.
        //This callback is a bridge to connect the TreeView and its child TreeViewItems.
        public Action<TreeViewItem, CustomEvent, System.Object> OnItemCustomEvent;
        //called when a TreeList reposition method finished.
        public Action<TreeList> OnTreeListRepositionFinish;
  •  ItemPrefab上绑定ItemPrefab脚本,用于绑定层级的基础结构expandBtn收缩、icon图标、labelText等。

3.新增ItemPrefab

        AddChildBtn按钮上绑定TreeManager的OnAddChildBtnClicked()方法。

        鼠标点击树形结构某一层级,层级显示选中状态。此时点击新增按钮,会在选中层级下创建新的层级目录。目录名为选中状态,修改名称,移开鼠标为非选中状态,保存层级。

  private void Update()
        {

            ///****************处理修改、新增层级,取消聚焦触发**********************************
            if (currentItem != null && currentItem.GetComponent<ItemScript>().IsSelected && inputFieldType)
            {
                int status = 1;
                int temp = -1;
                //增加log
                //LogInfo logInfo = new LogInfo();
                //logInfo.UserName = DataBase.Instance().loginUserInfo.UserName;
                inputFieldType = false;
                OutlineInfo outlineInfo = new OutlineInfo();
                outlineInfo.OutlineName = currentItem.GetComponent<ItemScript>().labelText.text;
                outlineInfo.ParentId = currentItem.GetComponent<ItemScript>().parentId;
                outlineInfo.Level = currentLevel;
                //新增
                if (string.IsNullOrEmpty(currentItem.GetComponent<ItemScript>().id))
                {
                    //temp = ServiceManager.Instance().AddOutlineInfo(outlineInfo);
                    //logInfo.OperationName = Common.outLineAddLog;
                }
                else
                {//修改
                    //outlineInfo.OutlineId = currentItem.GetComponent<ItemScript>().id;
                    //temp = ServiceManager.Instance().ChangeOutlineInfo(outlineInfo);
                    //logInfo.OperationName = Common.outLineEditLog;
                }
                if (temp == 0)
                {
                    status = 0;
                }
                //logInfo.UserName = DataBase.Instance().loginUserInfo.UserName;
                //logInfo.OperationStatus = status.ToString();
                //ServiceManager.Instance().AddLog(logInfo);
            }
        }

 public void OnAddChildBtnClicked()
        {
            mNewItemCount++;
            TreeViewItem childItem = new TreeViewItem();
            if (mTreeView.IsEmpty)
            {
                childItem = mTreeView.AppendItem("ItemPrefab1");
                childItem.GetComponent<ItemScript>().SetItemInfo("新建大纲", "新建大纲" + mNewItemCount);
            }
            else
            {
                TreeViewItem item = CurSelectedItem;
                if (item == null)
                {
                    Debug.Log("Please Select a Item First");
                    return;
                }
                childItem = item.ChildTree.AppendItem("ItemPrefab1");
                childItem.GetComponent<ItemScript>().parentId = item.GetComponent<ItemScript>().id;
                childItem.GetComponent<ItemScript>().labelText.text = "新建大纲";
                childItem.GetComponent<ItemScript>().SetItem(childItem.GetComponent<ItemScript>());

            }
            OnItemCustomEvent(childItem, CustomEvent.ItemClicked, "");
            childItem.GetComponent<ItemScript>().labelText.interactable = true;
            childItem.GetComponent<ItemScript>().labelText.Select();
            currentItem = childItem;

        }

4.修改ItemPrefab

        EditBtn按钮上绑定TreeManager的OnEditBtnClicked()方法。

        同样保证修改层级显示选中状态。此时点击修改按钮,目录名为选中状态,修改名称,移开鼠标为非选中状态,触发update方法,修改保存层级。

    public void OnEditBtnClicked()
        {
            TreeViewItem item = CurSelectedItem;
            if (item == null)
            {
                Debug.Log("Please Select a Item First");
                return;
            }
            item.GetComponent<ItemScript>().labelText.interactable = true;
            item.GetComponent<ItemScript>().labelText.Select();
            currentItem = item;
        }
        
    }

5.删除temPrefab

        DeleteBtn按钮上绑定TreeManager的OnDeleteBtnClicked()方法。

        删除层级为选中状态。此时点击删除按钮删除层级。注释掉部分代码,为操作数据库删除数据。

  public void OnDeleteBtnClicked()
        {
            TreeViewItem item = CurSelectedItem;
            if (item == null)
            {
                Debug.Log("Please Select a Item First");
                return;
            }
            List<string> outlineIds = new List<string>();
            outlineIds.Add(currentItemId);
            item.ParentTreeList.DeleteItem(item);

            ****************删除数据库数据*******************
            //int status = 1;
            //int temp = ServiceManager.Instance().DeleteOutlineInfo(outlineIds);
            //if (temp == 0)
            //{
            //    status = 0;
            //    item.ParentTreeList.DeleteItem(item);
            //}
            增加log
            //LogInfo logInfo = new LogInfo();
            //logInfo.UserName = DataBase.Instance().loginUserInfo.UserName;
            //logInfo.OperationStatus = status.ToString();
            //logInfo.OperationName = Common.outLineDeleteLog;
            //ServiceManager.Instance().AddLog(logInfo);
        }

总结

组件结构简单,层级明朗,便于理解。可更改ui和尺寸用于不同场合。个人总结归纳,便于使用。避免重复造轮子~~~

CSDN组件下载:https://download.csdn.net/download/u014641682/87630371

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Mtree is a powerful tree creation tool for the Unity editor. Nominated for best Artistic Tool 2019 Unity Awards. Every game needs vegetation, and while there are numerous vegetation packs for sale on the asset store, nothing beats the usefulness of having total control over the look and performance of the assets. Mtree will not only create beautiful looking vegetation, it will streamline your workflow by removing the need of modelling, unwrapping, importing your vegetation models from another software, and doing it all over again when you need to change a small detail. With Mtree, there will be less iterations over your models, and they will be quicker. Mtree trees are made in unity, for unity, the material is right, the dimensions are right, and everything is simple. Moreover, a good mesh is not enough in order to have a believable vegetation asset, you need a good shader, a good wind displacement solution, and vertex data to feed those; Mtree will answer every one of these needs. Mtree offers an intuitive, simple, yet complete solution for crafting AAA trees in a matter of minutes. With Mtree you can: • Create a trunk of any shape. • Add branches, grow them, split stem, add more branches. • Add leafs of any shape. • Bake the ambient occlusion in the vertex data. • Control the polygon count, get the most out of the fewest triangles. • Create Branches textures from a single leaf texture with the Branch Editor. • Save your finished tree as a prefab that is convenient to use. What Mtree will do for you: • Automatically create LOD levels. • Create and assign materials to the bark and leaves of your trees. • Make branches react to the colliders of your scene. • Create and render a billboard when you save the tree as prefab. • Bake the ambient occlusion when you save the tree as prefab. • Create vertex color data that will be used to drive the wind simulation and random color variation.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值