Unity外掛程式之NGUI學習(7)—— ScrollView(Panel),nguiscrollview
今天介紹的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。
Unity的NGUI列表彈出效果做不出來解答
你的subpanel是scrollview嗎?
【急】(unity3d)NGUI的UI root下面的adjust by DPI到底是什??
官網論壇上的回答:
Adjust by DPI experimental option will scale your UI Root on top of its ordinary scaling. That is, you'd design your UI in Pixel Perfect mode and on iPad Retina you'd get the screen size that matches the non-retina resolution. It basically takes pixel density into consideration, making your UI be based on screen DPI, not just screen resolution.
簡單的說,就是不同的顯示裝置有不同的DPI,所謂DPI是用來衡量像素密度的,比如3.7寸的解析度為1024*768的android裝置就是
sqrt(1024^2 + 768^2) / 3.7
由此可見,相同解析度下,螢幕越小,DPI越大。而相同螢幕大小下,解析度越大,DPI越大。
NGUI的這個功能就是可以動態匹配其它DPI的螢幕,而你只需要匹配開發機的DPI就可以了。NGUI會通過內部計算來匹配目標裝置的DPI(比如展開/縮小控制項)不過實際使用上問題還是很多的。