unity 程序做一个折叠菜单

第一次遇到这种需求,本来以为很难,没想到试了一下以后没啥难度,所以记录一下

首先新建一个scroll view,然后在content里面添加vertical layout group和content size fitter这两个组件。(vertical layout group 的 spacing要设置成10左右,这一步是关键)

然后在content里面放几个按钮,充当标题栏和内容栏

然后在脚本中给按钮赋值,这样就可以使用代码控制按钮了

cs 复制代码
public Button 标题;
public Button 内容1;
public Button 内容2;
public Button 标题2;
public Button 内容3;
public Button 内容4;

// Start is called before the first frame update
void Start()
{
    标题.onClick.AddListener(new UnityEngine.Events.UnityAction(ShowOrHideBtn));
    标题2.onClick.AddListener(new UnityEngine.Events.UnityAction(ShowOrHideBtn2));
}

// Update is called once per frame
void Update()
{
    
}

private void ShowOrHideBtn()
{
    if(内容1.gameObject.activeSelf)
    {
        内容1.transform.DOScaleY(0, 0.3f).OnComplete(() => { 内容1.transform.gameObject.SetActive(false); });
        内容2.transform.DOScaleY(0, 0.3f).OnComplete(() => { 内容2.transform.gameObject.SetActive(false); });
    }
    else
    {
        内容1.transform.gameObject.SetActive(true);
        内容1.transform.DOScaleY(1, 0.3f);

        内容2.transform.gameObject.SetActive(true);
        内容2.transform.DOScaleY(1, 0.3f);
    }
}

private void ShowOrHideBtn2()
{
    if (内容3.gameObject.activeSelf)
    {
        内容3.transform.DOScaleY(0, 0.3f).OnComplete(() => { 内容3.transform.gameObject.SetActive(false); });
        内容4.transform.DOScaleY(0, 0.3f).OnComplete(() => { 内容4.transform.gameObject.SetActive(false); });
    }
    else
    {
        内容3.transform.gameObject.SetActive(true);
        内容3.transform.DOScaleY(1, 0.3f);

        内容4.transform.gameObject.SetActive(true);
        内容4.transform.DOScaleY(1, 0.3f);
    }
}

效果如下:

相关推荐
xcLeigh1 天前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
DaLiangChen2 天前
Vuforia 地面识别案例
unity·ar
江畔柳前堤2 天前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
魔术师Dix2 天前
一个轮子:Luban Skill 制作演示
游戏·unity·ai编程
xcLeigh3 天前
Unity基础:Light灯光组件入门——Directional Light、Point Light与Spotlight
unity·游戏引擎·教程
郝学胜-神的一滴3 天前
[简化版 GAMES 104] 现代游戏引擎 04:从0到1构建你的游戏世界
c++·游戏·unity·游戏引擎·软件工程·unreal engine
是嘟嘟啊4 天前
【Unity DOTS】EntityCommandBuffer 与 JobHandle
unity·ecs·dots·unity dots·job·burst·burstjob
xcLeigh4 天前
Unity基础:Camera相机组件详解——透视投影与正交投影的区别
数码相机·unity·游戏引擎
玖玥拾4 天前
Unity3D RPG 入门项目(二)移动 Bug 修复、环绕相机、NPC 任务系统、UI 穿透处理
unity·游戏引擎