Scroll View控制菜单栏的伸缩

一:操作篇

在Cavas 添加Scroll View,想要横排的物品栏。在Viewport 下的Content上添加组件:Grid Layout Grop和Content Size Fitter

在Content下添加button,

Content:计算要显示物品栏的多少

二:代码篇

   //所有的父(第一级主)菜单
    public List allObj = new List();
    Vector2 contentSizeData;//每次计算Content的所容纳的数量
    RectTransform contentRt;
    GameObject lastObj;//最后一次点击的父菜单
    void Start ()
    {
        List child = new List();//所有子类菜单
        child.Add(GameObject.Find("Button (1)"));
        child.Add(GameObject.Find("Button (2)"));
        child.Add(GameObject.Find("Button (3)"));
        child.Add(GameObject.Find("Button (4)"));
        child.Add(GameObject.Find("Button (5)"));
        child.Add(GameObject.Find("Button (6)"));
        child.Add(GameObject.Find("Button (7)"));
        child.Add(GameObject.Find("Button (8)"));
        child.Add(GameObject.Find("Button (9)"));
        child.Add(GameObject.Find("Button (10)"));
        child.Add(GameObject.Find("Button (11)"));
        child.Add(GameObject.Find("Button (12)"));
        child.Add(GameObject.Find("Button (13)"));
        child.Add(GameObject.Find("Button (14)"));
        child.Add(GameObject.Find("Button (15)"));
        child.Add(GameObject.Find("Button (16)"));
        child.Add(GameObject.Find("Button (17)"));
        child.Add(GameObject.Find("Button (18)"));
        child.Add(GameObject.Find("Button (19)"));
        child.Add(GameObject.Find("Button (20)"));
        AddItem(GameObject.Find("Button"), child);
        Init();
    }
    ///
    /// 初始化
    ///

    void Init()
    {
        lastObj = null;
        contentRt = GameObject.Find("Canvas/MY Scroll View/Viewport/Content").GetComponent();
        contentSizeData = contentRt.sizeDelta;
        contentSizeData.y = 0;
        for (int i = 0; i < allObj.Count; i++)
        {
            ChildListState(allObj[i], 0, false);
            contentSizeData.y += allObj[i].GetComponent().sizeDelta.y;
        }
        contentRt.sizeDelta = contentSizeData;
    }
    ///
    /// 加入一个父菜单和子菜单
    ///

    /// 父菜单物体
    /// 子菜单
    private void AddItem(GameObject parent, List childList)
    {                                                    //(应用委托,传一个方法)
        parent.GetComponent
        if (lastObj != null)
        {
            if (lastObj != item)
            {
                if (lastObj.GetComponent().childList[0].activeSelf)
                    ChildListState(lastObj, 2, true);
            }
        }
        lastObj = item;
    }

你可能感兴趣的:(Scroll,View控控件,Unity,UGUI,Cavas)