28 Feb 2020
24852字
83分
次
Unity3D
BY-SA 4.0(除特别声明或转载文章外)
一、前言
层级菜单在Unity中用到的并不多,主要是做分类的时候用的比较多,今天就给大家分享几个层级代码,扩充一下,写成插件也是不错的。
首先看一下效果吧:
1.
2.
3.
4.
5.
二、资源下载
源文件:
https://download.csdn.net/download/q764424567/11644500
三、正文
### 第一种实现效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830161902402.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
实现原理:这个是用系统自带的UGUI Scroll View组件,脚本控制创建父物体,父物体身上挂载有初始化子物体的脚本
优缺点:
优点是实现简单,不需要多与的插件,代码量也不大,控制比较方便
缺点是只能实现两个层级的显示
实现过程:
1、新建一个Scrpll View
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830163556542.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
2、制作预制体
界面就这么设计就行:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830164915743.png)
名字改一下
Content:父节点容器
ParentMenu:父节点
TextParent:父节点文本
ChildMenu:子节点容器
item:子节点
TextChild:子节点文本
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830164024475.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
然后将父节点改名字叫parentMenu,做成预制体:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830164104546.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
预制体放到Resources文件夹中:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830164115254.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
将子物体也制作成预制体:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190830164217544.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E3NjQ0MjQ1Njc=,size_16,color_FFFFFF,t_70)
3、编写脚本ParentMenu.cs
这个脚本主要是作用是创建子物体:
```csharp
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ParentMenu : MonoBehaviour
{
private GameObject childMenu;//子菜单的parent
private RectTransform[] childs;//所有子菜单的rect
private RectTransform itemRect;//子菜单的prefab
private Vector3 offset;//单个子菜单的高度
private int count;//子菜单的个数
public bool isOpening { get; private set; }//父菜单是否展开
public bool isCanClick { get; set; }//父菜单是否可以点击
public void Init(RectTransform rect, int count)
{
//找到子节点
childMenu = transform.Find("childMenu").gameObject;
itemRect = rect;
this.count = count;
childs = new RectTransform[this.count];
offset = new Vector3(0, itemRect.rect.height);
for (int i = 0; i < this.count; i++)
{
childs[i] = Instantiate(itemRect, childMenu.transform);
}
childMenu.gameObject.SetActive(false);
isOpening = false;
isCanClick = true;
GetComponent