UGUI动态滑动列表

来源:互联网 发布:机械行业erp软件哪家好 编辑:程序博客网 时间:2024/06/07 02:51

目录结构


Image  增加控件  ScrollRect


Content 增加VerticalLayoutGroup


预制体





详细代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class initMessage : MonoBehaviour {
    List<GameObject> message = new List<GameObject>();
    public GameObject item;
    public Button cancel;
    GameObject myMessage;
    GameObject parent;
    Vector3 itemLocalPos;
    Vector2 contentSize;
    float itemHeight;
// Use this for initialization
void Start () {
        parent = GameObject.Find("Content");
        contentSize = parent.GetComponent<RectTransform>().sizeDelta;
        item = Resources.Load("Prefabs/List_1") as GameObject;
        itemHeight = item.GetComponent<RectTransform>().rect.height;
        itemLocalPos = item.transform.localPosition;


        for (int i = 0; i < 8; i++)
        {
            AddItem(i);
        }
    }

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

}


    public void AddItem(int index)
    {
        GameObject a = Instantiate(item) as GameObject;
        a.GetComponent<Transform>().SetParent(parent.GetComponent<Transform>(), false);
        a.transform.localPosition = new Vector3(itemLocalPos.x, itemLocalPos.y - message.Count * itemHeight,0);
        message.Add(a);
        parent.transform.GetChild(index).transform.Find("jujue").GetComponent<Button>().onClick.AddListener(delegate { RemoveItem(a); });
        Debug.Log(parent.transform.GetChild(index).transform.Find("jujue").GetComponent<Button>().name);
        if(contentSize.y <= message.Count * itemHeight)
        {
            parent.GetComponent<RectTransform>().sizeDelta = new Vector2(contentSize.x, message.Count * itemHeight);
        }
    }


    public void RemoveItem(GameObject t)
    {
        int index = message.IndexOf(t);
        message.Remove(t);
        Destroy(t);
        for(int i = index;i < message.Count; i++)
        {
            message[i].transform.localPosition += new Vector3(0, itemHeight, 0);
        }
        if(contentSize.y <= message.Count * itemHeight)
        {
            parent.GetComponent<RectTransform>().sizeDelta = new Vector2(contentSize.x,message.Count * itemHeight);
        }
        else
        {
            parent.GetComponent<RectTransform>().sizeDelta = contentSize;
        }
    }
}

原创粉丝点击