Unity插件之NGUI学习(7)—— ScrollView(Panel)

来源:互联网 发布:串口通讯51单片机 编辑:程序博客网 时间:2024/05/17 00:16

今天介绍的ScrollView,参考的是NGUI(3.6.8)中的Example项目:Scroll View(Panel)。

先按照Unity插件之NGUI学习(2)创建一个UI Root,然后在UI Root下面创建一个Scroll View,选择菜单NGUI->Create->Scroll View

然后在Inspector窗口做一些参数设置


Movement设置滚动Vertical纵向或者horizontal横向。

Scroll Bars可以添加纵向或者横向的滚动条控件(在这个项目中暂且不添加)。

在UI Panel可以设置滚动的的显示范围,Clipping可以选择Soft Clip,设置Size的大小,在预览窗口,就能看到亮紫色就是滚动Panel的显示区域。


在Hierarchy窗口选择Scroll View,在菜单中选择NGUI->Create->Grid,然后在Hierarchy窗口选择刚创建的Grid,在菜单Component->NGUI->Interaction->Center Scroll View on Child。


设置单个Item Cell的高度和宽度,Arrangment设置纵向还是横向的。


然后制作一个ListItem的Prefab,高度和宽度要跟上面Grid的Cell Width、Cell Height要一致,需要给ListItem添加2个重要的脚本和Box Collider,可以实现滚动效果,以及Item点击后自动调整滚动位置。脚本的添加,在菜单中选择Commponent->NGUI->Interaction->Drag Scroll View和Commponent->NGUI->Interaction->Center Scroll View on Click。Box Collider添加后,勾选Is Trigger。


然后在Hierarchy窗口的UIGrid下,添加多个ListItem,然后点击运行,就可以看到滚动效果,点击单个Item,滚动会自动调整位置。


下面介绍下代码动态调整Scroll View的Item数量。

首先添加2个按钮,一个AddButton,一个DelButton,然后创建一个ListViewTest脚本。



ListViewTest代码如下:

using UnityEngine;
using System.Collections;


public class ListViewTest : MonoBehaviour {


private GameObject scrollView;
private UIGrid grid;
private UIButton addBtn, delBtn;


// Use this for initialization
void Start () {
scrollView = GameObject.Find("Scroll View");
grid = scrollView.GetComponentInChildren <UIGrid>();
addBtn = GameObject.Find("AddButton").GetComponent<UIButton>();
delBtn = GameObject.Find("DelButton").GetComponent<UIButton>();
EventDelegate.Add(addBtn.onClick, AddItem);
EventDelegate.Add(delBtn.onClick, DelAllItems);
}

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

}


void AddItem() {
int count = grid.transform.childCount + 1;
//克隆预设
GameObject o = (GameObject)Instantiate(Resources.Load("Prefabs/ListItem"));
UILabel label = o.GetComponentInChildren<UILabel>();
//为每个预设设置一个独一无二的名称
label.text = "item" + count;
//将新预设放在Panel对象下面
o.transform.parent = grid.transform;
//下面这段代码很重要,是因为创建预设时 会自动修改旋转缩放的系数,
//我不知道为什么会自动修改,所以重新为它赋值
o.transform.localPosition = Vector3.zero;
o.transform.localScale = new Vector3(1, 1, 1);
//列表添加后用于刷新listView
grid.repositionNow = true;
}


void DelAllItems() {
foreach (Transform trans in grid.transform) {
Destroy(trans.gameObject);
}
grid.repositionNow = true;
}
}

把脚本绑定在UI Root后运行游戏,点击Add按钮,可以增加Item,点击Del按钮,会删除所有的Item。

1 0
原创粉丝点击