位置: 编程技术 - 正文
推荐整理分享Unity UIScrollView优化,希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!
转载自: 发现如果数据量大了。NGUI就会创建大量的GameObject. 这样肯定对性能消耗影响巨大,所以我自己优化了一下。这样效率可以提高很多。当然,优化过后UIGrid还是有一些不足,可惜暂时没有思路,以后有思路了。再接着继续。直接贴代码。
Demo : game.gamerisker.com/grid/
DownLoad : GridDemo 访问密码: o7bf
CustomGrid.csC#using UnityEngine;using System.Collections;using System.Collections.Generic; /// <summary>/// @author : YangDan/// @date : -6-/// /// CustomGrid,这个类主要做了一件事,就是优化了,NGUI UIGrid 在数据量很多都时候,///创建过多都GameObject对象,造成资源浪费./// 该类需要和 CustomScrollView.cs 以及 CustomDragScrollView.cs一起使用;/// CustomScrollView 类只上把bounds字段给暴露出来,因为bounds都大小需要在外面设置了./// CustomDragScrollView 类 没有修改,///因为默认都UIDragScrollView 默认里面调用都上UIScrollView ///不能与我们都CustomScrollView兼容./// 所以只是将里面都UIScrollView 改为 CustomScrollView./// Item 是一个渲染操作类.可以自己定义,或者不要,并没有影响./// </summary>/// public class CustomGrid : UIWidgetContainer{ public GameObject Item; public int m_cellHeight = ; public int m_cellWidth = ; private float m_height; private int m_maxLine; private Item[] m_cellList; private CustomScrollView mDrag; private float lastY = -1; private List<string> m_listData; private Vector3 defaultVec; void Awake() { m_listData = new List<string>(); defaultVec = new Vector3(0, m_cellHeight, 0); mDrag = NGUITools.FindInParents<CustomScrollView>(gameObject); m_height = mDrag.panel.height; m_maxLine = Mathf.CeilToInt(m_height / m_cellHeight) + 1; m_cellList = new Item[m_maxLine]; CreateItem(); } void Update() { if (mDrag.transform.localPosition.y != lastY) { Validate(); lastY = mDrag.transform.localPosition.y; } } private void UpdateBounds(int count) { Vector3 vMin = new Vector3(); vMin.x = -transform.localPosition.x; vMin.y = transform.localPosition.y - count * m_cellHeight; vMin.z = transform.localPosition.z; Bounds b = new Bounds(vMin, Vector3.one); b.Encapsulate(transform.localPosition); mDrag.bounds = b; mDrag.UpdateScrollbars(true); mDrag.RestrictWithinBounds(true); } public void AddItem(string name) { m_listData.Add(name); Validate(); UpdateBounds(m_listData.Count); } private void Validate() { Vector3 position = mDrag.panel.transform.localPosition; float _ver = Mathf.Max(position.y, 0); int startIndex = Mathf.FloorToInt(_ver / m_cellHeight); int endIndex = Mathf.Min(m_listData.Count, startIndex + m_maxLine); Item cell; int index = 0; for (int i = startIndex; i < startIndex + m_maxLine; i++) { cell = m_cellList[index]; if (i < endIndex) { cell.text = m_listData[i]; cell.transform.localPosition = new Vector3(0, i * -m_cellHeight, 0); cell.gameObject.SetActive(true); } else { cell.transform.localPosition = defaultVec; } index++; } } private void CreateItem() { for (int i = 0; i < m_maxLine; i++) { GameObject go; go = Instantiate(Item) as GameObject; go.transform.parent = transform; go.transform.localScale = Vector3.one; go.SetActive(false); go.name = "Item" + i; Item item = go.GetComponent<Item>(); item.Init(); m_cellList[i] = item; } }}Main.csC#usingUnityEngine;usingSystem.Collections; /// <summary>/// 主初始化类/// </summary>publicclassMain:MonoBehaviour{ publicintcount; publicboolisUpdate=true; privateCustomGridgrid; privateintindex=0; privateinti=0; privateUILabellabel; voidAwake() { grid=GetComponentInChildren<CustomGrid>(); label=transform.FindChild("back/back/Label").GetComponent<UILabel>(); } voidStart() { while(i<count) { Add(""i); } label.text=string.Format("创建 {0} 个Item",i.ToString());} voidUpdate() { if(isUpdate) { if(index%==0) { Add(i.ToString()); i; label.text=string.Format("创建 {0} 个Item",i.ToString()); } index; } } privatevoidAdd(stringtext) { grid.AddItem(text); }}
Item.csC#using UnityEngine;using System.Collections;using System.Collections.Generic;using System.Text.RegularExpressions; /// <summary>/// 子渲染处理类/// </summary>public class Item : MonoBehaviour { private UILabel label; public void Init() { label = transform.FindChild("Label").GetComponent<UILabel>(); } /// <summary> /// 文本内容 /// </summary> public string text { set { label.text = value; } }}
CustomScrollView.csusingUnityEngine; /// <summary>/// 自定义ScrollView 和 UIScrollView 基本相同/// </summary>publicclassCustomScrollView:MonoBehaviour{publicenumMovement{Horizontal,Vertical,Unrestricted,Custom,} publicenumDragEffect{None,Momentum,MomentumAndSpring,} publicenumShowCondition{Always,OnlyIfNeeded,WhenDragging,} publicdelegatevoidOnDragFinished(); publicMovementmovement=Movement.Vertical; publicDragEffectdragEffect=DragEffect.MomentumAndSpring; publicboolrestrictWithinPanel=true; publicbooldisableDragIfFits=false; publicboolsmoothDragStart=true; publicbooliOSDragEmulation=true; publicfloatscrollWheelFactor=0.f; publicfloatmomentumAmount=f;publicUIScrollBarhorizontalScrollBar; publicUIScrollBarverticalScrollBar; publicShowConditionshowScrollBars=ShowCondition.OnlyIfNeeded; publicVector2customMovement=newVector2(1f,0f); publicVector2relativePositionOnReset=Vector2.zero; publicOnDragFinishedonDragFinished; [HideInInspector][SerializeField]Vector3scale=newVector3(0f,0f,0f); TransformmTrans;UIPanelmPanel;PlanemPlane;Vector3mLastPos;boolmPressed=false;Vector3mMomentum=Vector3.zero;floatmScroll=0f;BoundsmBounds; //bool mCalculatedBounds = false;boolmShouldMove=false;boolmIgnoreCallbacks=false;intmDragID=-;Vector2mDragStartOffset=Vector2.zero;boolmDragStarted=false; publicUIPanelpanel{get{returnmPanel;}} publicBoundsbounds{get{ returnmBounds;} set { mBounds=value; }} publicboolcanMoveHorizontally{get{returnmovement==Movement.Horizontal||movement==Movement.Unrestricted||(movement==Movement.Custom&&customMovement.x!=0f);}} publicboolcanMoveVertically{get{returnmovement==Movement.Vertical||movement==Movement.Unrestricted||(movement==Movement.Custom&&customMovement.y!=0f);}} publicvirtualboolshouldMoveHorizontally{get{floatsize=bounds.size.x;if(mPanel.clipping==UIDrawCall.Clipping.SoftClip)size=mPanel.clipSoftness.x *2f;returnsize>mPanel.width;}} publicvirtualboolshouldMoveVertically{get{floatsize=bounds.size.y;if(mPanel.clipping==UIDrawCall.Clipping.SoftClip)size=mPanel.clipSoftness.y *2f;returnsize>mPanel.height;}} protectedvirtualboolshouldMove{get{if(!disableDragIfFits)returntrue; if(mPanel==null)mPanel=GetComponent<UIPanel>();Vector4clip=mPanel.finalClipRegion;Boundsb=bounds; floathx=(clip.z==0f)?Screen.width :clip.z *0.5f;floathy=(clip.w==0f)?Screen.height:clip.w *0.5f; if(canMoveHorizontally){if(b.min.x<clip.x-hx)returntrue;if(b.max.x>clip.xhx)returntrue;} if(canMoveVertically){if(b.min.y<clip.y-hy)returntrue;if(b.max.y>clip.yhy)returntrue;}returnfalse;}} publicVector3currentMomentum{get{returnmMomentum;}set{mMomentum=value;mShouldMove=true;}} voidAwake(){mTrans=transform;mPanel=GetComponent<UIPanel>(); if(mPanel.clipping==UIDrawCall.Clipping.None)mPanel.clipping=UIDrawCall.Clipping.ConstrainButDontClip;if(movement!=Movement.Custom&&scale.sqrMagnitude>0.f){if(scale.x==1f&&scale.y==0f){movement=Movement.Horizontal;}elseif(scale.x==0f&&scale.y==1f){movement=Movement.Vertical;}elseif(scale.x==1f&&scale.y==1f){movement=Movement.Unrestricted;}else{movement=Movement.Custom;customMovement.x=scale.x;customMovement.y=scale.y;}scale=Vector3.zero;#if UNITY_EDITORUnityEditor.EditorUtility.SetDirty(this);#endif}if(Application.isPlaying)mPanel.onChange=OnPanelChange;} voidOnDestroy(){if(Application.isPlaying&&mPanel!=null)mPanel.onChange-=OnPanelChange;} voidOnPanelChange(){UpdateScrollbars(true);} voidStart(){if(Application.isPlaying){UpdateScrollbars(true); if(horizontalScrollBar!=null){EventDelegate.Add(horizontalScrollBar.onChange,OnHorizontalBar);horizontalScrollBar.alpha=((showScrollBars==ShowCondition.Always)||shouldMoveHorizontally)?1f:0f;} if(verticalScrollBar!=null){EventDelegate.Add(verticalScrollBar.onChange,OnVerticalBar);verticalScrollBar.alpha=((showScrollBars==ShowCondition.Always)||shouldMoveVertically)?1f:0f;}}} publicboolRestrictWithinBounds(boolinstant){returnRestrictWithinBounds(instant,true,true);} publicboolRestrictWithinBounds(boolinstant,boolhorizontal,boolvertical){Boundsb=bounds;Vector3constraint=mPanel.CalculateConstrainOffset(b.min,b.max); if(!horizontal)constraint.x=0f;if(!vertical)constraint.y=0f; if(constraint.magnitude>1f){if(!instant&&dragEffect==DragEffect.MomentumAndSpring){Vector3pos=mTrans.localPositionconstraint;pos.x=Mathf.Round(pos.x);pos.y=Mathf.Round(pos.y);SpringPanel.Begin(mPanel.gameObject,pos,f);}else{MoveRelative(constraint);mMomentum=Vector3.zero;mScroll=0f;}returntrue;}returnfalse;} publicvoidDisableSpring(){SpringPanelsp=GetComponent<SpringPanel>();if(sp!=null)sp.enabled=false;} publicvirtualvoidUpdateScrollbars(boolrecalculateBounds){if(mPanel==null)return; if(horizontalScrollBar!=null||verticalScrollBar!=null){if(recalculateBounds){ //mCalculatedBounds = false;mShouldMove=shouldMove;} Boundsb=bounds;Vector2bmin=b.min;Vector2bmax=b.max; if(horizontalScrollBar!=null&&bmax.x>bmin.x){Vector4clip=mPanel.finalClipRegion;floatextents=clip.z *0.5f; if(mPanel.clipping==UIDrawCall.Clipping.SoftClip)extents-=mPanel.clipSoftness.x; floatmin=clip.x-extents-b.min.x;floatmax=b.max.x-extents-clip.x; floatwidth=bmax.x-bmin.x;min=Mathf.Clamp(min/width);max=Mathf.Clamp(max/width); floatsum=minmax;mIgnoreCallbacks=true;horizontalScrollBar.barSize=1f-sum;horizontalScrollBar.value=(sum>0.f)?min/sum:0f;mIgnoreCallbacks=false;} if(verticalScrollBar!=null&&bmax.y>bmin.y){Vector4clip=mPanel.finalClipRegion;floatextents=clip.w *0.5f; if(mPanel.clipping==UIDrawCall.Clipping.SoftClip)extents-=mPanel.clipSoftness.y; floatmin=clip.y-extents-bmin.y;floatmax=bmax.y-extents-clip.y; floatheight=bmax.y-bmin.y;min=Mathf.Clamp(min/height);max=Mathf.Clamp(max/height);floatsum=minmax; mIgnoreCallbacks=true;verticalScrollBar.barSize=1f-sum;verticalScrollBar.value=(sum>0.f)?1f-min/sum:0f;mIgnoreCallbacks=false;}}elseif(recalculateBounds){ //mCalculatedBounds = false;}} publicvirtualvoidSetDragAmount(floatx,floaty,boolupdateScrollbars){DisableSpring(); Boundsb=bounds;if(b.min.x==b.max.x||b.min.y==b.max.y)return; Vector4clip=mPanel.finalClipRegion;clip.x=Mathf.Round(clip.x);clip.y=Mathf.Round(clip.y);clip.z=Mathf.Round(clip.z);clip.w=Mathf.Round(clip.w); floathx=clip.z *0.5f;floathy=clip.w *0.5f;floatleft=b.min.xhx;floatright=b.max.x-hx;floatbottom=b.min.yhy;floattop=b.max.y-hy; if(mPanel.clipping==UIDrawCall.Clipping.SoftClip){left-=mPanel.clipSoftness.x;right=mPanel.clipSoftness.x;bottom-=mPanel.clipSoftness.y;top=mPanel.clipSoftness.y;} floatox=Mathf.Lerp(left,right,x);floatoy=Mathf.Lerp(top,bottom,y); ox=Mathf.Round(ox);oy=Mathf.Round(oy); if(!updateScrollbars){Vector3pos=mTrans.localPosition;if(canMoveHorizontally)pos.x=clip.x-ox;if(canMoveVertically)pos.y=clip.y-oy;mTrans.localPosition=pos;} if(canMoveHorizontally)clip.x=ox;if(canMoveVertically)clip.y=oy; Vector4cr=mPanel.baseClipRegion;mPanel.clipOffset=newVector2(clip.x-cr.x,clip.y-cr.y); if(updateScrollbars)UpdateScrollbars(false);} publicvoidResetPosition(){if(NGUITools.GetActive(this)){ //mCalculatedBounds = false;SetDragAmount(relativePositionOnReset.x,relativePositionOnReset.y,false);SetDragAmount(relativePositionOnReset.x,relativePositionOnReset.y,true);}} voidOnHorizontalBar(){if(!mIgnoreCallbacks){floatx=(horizontalScrollBar!=null)?horizontalScrollBar.value:0f;floaty=(verticalScrollBar!=null)?verticalScrollBar.value:0f;SetDragAmount(x,y,false);}} voidOnVerticalBar(){if(!mIgnoreCallbacks){floatx=(horizontalScrollBar!=null)?horizontalScrollBar.value:0f;floaty=(verticalScrollBar!=null)?verticalScrollBar.value:0f;SetDragAmount(x,y,false);}} publicvirtualvoidMoveRelative(Vector3relative){mTrans.localPosition=relative;Vector2co=mPanel.clipOffset;co.x-=relative.x;co.y-=relative.y;mPanel.clipOffset=co;UpdateScrollbars(false);} publicvoidMoveAbsolute(Vector3absolute){Vector3a=mTrans.InverseTransformPoint(absolute);Vector3b=mTrans.InverseTransformPoint(Vector3.zero);MoveRelative(a-b);} publicvoidPress(boolpressed){if(smoothDragStart&&pressed){mDragStarted=false;mDragStartOffset=Vector2.zero;} if(enabled&&NGUITools.GetActive(gameObject)){if(!pressed&&mDragID==UICamera.currentTouchID)mDragID=-; //mCalculatedBounds = false;mShouldMove=shouldMove;if(!mShouldMove)return;mPressed=pressed; if(pressed){// Remove all momentum on pressmMomentum=Vector3.zero;mScroll=0f; // Disable the spring movementDisableSpring(); // Remember the hit positionmLastPos=UICamera.lastHit.point; // Create the plane to drag alongmPlane=newPlane(mTrans.rotation *Vector3.back,mLastPos); // Ensure that we're working with whole numbers, keeping everything pixel-perfectVector2co=mPanel.clipOffset;co.x=Mathf.Round(co.x);co.y=Mathf.Round(co.y);mPanel.clipOffset=co; Vector3v=mTrans.localPosition;v.x=Mathf.Round(v.x);v.y=Mathf.Round(v.y);mTrans.localPosition=v;}else{if(restrictWithinPanel&&mPanel.clipping!=UIDrawCall.Clipping.None&&dragEffect==DragEffect.MomentumAndSpring)RestrictWithinBounds(false,canMoveHorizontally,canMoveVertically); if(!smoothDragStart||mDragStarted){if(onDragFinished!=null)onDragFinished();}}}} publicvoidDrag(){if(enabled&&NGUITools.GetActive(gameObject)&&mShouldMove){if(mDragID==-)mDragID=UICamera.currentTouchID;UICamera.currentTouch.clickNotification=UICamera.ClickNotification.BasedOnDelta; // Prevents the drag "jump". Contributed by 'mixd' from the Tasharen forums.if(smoothDragStart&&!mDragStarted){mDragStarted=true;mDragStartOffset=UICamera.currentTouch.totalDelta;} Rayray=smoothDragStart?UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos-mDragStartOffset):UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos); floatdist=0f; if(mPlane.Raycast(ray,outdist)){Vector3currentPos=ray.GetPoint(dist);Vector3offset=currentPos-mLastPos;mLastPos=currentPos; if(offset.x!=0f||offset.y!=0f){offset=mTrans.InverseTransformDirection(offset); if(movement==Movement.Horizontal){offset.y=0f;offset.z=0f;}elseif(movement==Movement.Vertical){offset.x=0f;offset.z=0f;}elseif(movement==Movement.Unrestricted){offset.z=0f;}else{offset.Scale((Vector3)customMovement);}offset=mTrans.TransformDirection(offset);} // Adjust the momentummMomentum=Vector3.Lerp(mMomentum,mMomentumoffset *(0.f*momentumAmount),0.f); // Move the scroll viewif(!iOSDragEmulation){MoveAbsolute(offset);}else{Vector3constraint=mPanel.CalculateConstrainOffset(bounds.min,bounds.max); if(constraint.magnitude>1f){MoveAbsolute(offset *0.5f);mMomentum *=0.5f;}else{MoveAbsolute(offset);}} // We want to constrain the UI to be within boundsif(restrictWithinPanel&&mPanel.clipping!=UIDrawCall.Clipping.None&&dragEffect!=DragEffect.MomentumAndSpring){RestrictWithinBounds(true,canMoveHorizontally,canMoveVertically);}}}} publicvoidScroll(floatdelta){if(enabled&&NGUITools.GetActive(gameObject)&&scrollWheelFactor!=0f){DisableSpring();mShouldMove=shouldMove;if(Mathf.Sign(mScroll)!=Mathf.Sign(delta))mScroll=0f;mScroll=delta *scrollWheelFactor;}} voidLateUpdate(){if(!Application.isPlaying)return;floatdelta=RealTime.deltaTime; // Fade the scroll bars if neededif(showScrollBars!=ShowCondition.Always){boolvertical=false;boolhorizontal=false; if(showScrollBars!=ShowCondition.WhenDragging||mDragID!=-||mMomentum.magnitude>0.f){vertical=shouldMoveVertically;horizontal=shouldMoveHorizontally;} if(verticalScrollBar){floatalpha=verticalScrollBar.alpha;alpha=vertical?delta *6f:-delta *3f;alpha=Mathf.Clamp(alpha);if(verticalScrollBar.alpha!=alpha)verticalScrollBar.alpha=alpha;} if(horizontalScrollBar){floatalpha=horizontalScrollBar.alpha;alpha=horizontal?delta *6f:-delta *3f;alpha=Mathf.Clamp(alpha);if(horizontalScrollBar.alpha!=alpha)horizontalScrollBar.alpha=alpha;}} // Apply momentumif(mShouldMove&&!mPressed){if(movement==Movement.Horizontal||movement==Movement.Unrestricted){mMomentum-=mTrans.TransformDirection(newVector3(mScroll *0.f,0f,0f));}elseif(movement==Movement.Vertical){mMomentum-=mTrans.TransformDirection(newVector3(0f,mScroll *0.f,0f));}else{mMomentum-=mTrans.TransformDirection(newVector3(mScroll *customMovement.x *0.f,mScroll *customMovement.y *0.f,0f));} if(mMomentum.magnitude>0.f){mScroll=NGUIMath.SpringLerp(mScroll,0f,f,delta); // Move the scroll viewVector3offset=NGUIMath.SpringDampen(refmMomentum,9f,delta);MoveAbsolute(offset); // Restrict the contents to be within the scroll view's boundsif(restrictWithinPanel&&mPanel.clipping!=UIDrawCall.Clipping.None)RestrictWithinBounds(false,canMoveHorizontally,canMoveVertically);if(mMomentum.magnitude<0.f&&onDragFinished!=null)onDragFinished();return;}else{mScroll=0f;mMomentum=Vector3.zero;}}elsemScroll=0f; // Dampen the momentumNGUIMath.SpringDampen(refmMomentum,9f,delta);} #if UNITY_EDITOR /// <summary> /// Draw a visible orange outline of the bounds. /// </summary> voidOnDrawGizmos() { if(mPanel!=null) { Boundsb=bounds; Gizmos.matrix=transform.localToWorldMatrix; Gizmos.color=newColor(1f,0.4f,0f); Gizmos.DrawWireCube(newVector3(b.center.x,b.center.y,b.min.z),newVector3(b.size.x,b.size.y,0f)); } }#endif}
CustomDragScrollView.csC#usingUnityEngine;usingSystem.Collections; /// <summary>/// 子类拖到处理类/// </summary>publicclassCustomDragScrollView:MonoBehaviour{ publicCustomScrollViewscrollView; [HideInInspector] [SerializeField] CustomScrollViewdraggablePanel; TransformmTrans; CustomScrollViewmScroll;boolmAutoFind=false; voidOnEnable(){mTrans=transform; if(scrollView==null&&draggablePanel!=null){scrollView=draggablePanel;draggablePanel=null;}FindScrollView();} voidFindScrollView(){ CustomScrollViewsv=NGUITools.FindInParents<CustomScrollView>(mTrans); if(scrollView==null){scrollView=sv;mAutoFind=true;}elseif(scrollView==sv){mAutoFind=true;}mScroll=scrollView;} voidStart(){FindScrollView();} voidOnPress(boolpressed){if(mAutoFind&&mScroll!=scrollView){mScroll=scrollView;mAutoFind=false;} if(scrollView&&enabled&&NGUITools.GetActive(gameObject)){scrollView.Press(pressed);if(!pressed&&mAutoFind){ scrollView=NGUITools.FindInParents<CustomScrollView>(mTrans);mScroll=scrollView;}}} voidOnDrag(Vector2delta){if(scrollView&&NGUITools.GetActive(this))scrollView.Drag();} voidOnScroll(floatdelta){if(scrollView&&NGUITools.GetActive(this))scrollView.Scroll(delta);}}
unity3d 在线更新资源(3) 确定方案后马上就碰到了一个新问题,那就是解压缩的时候太占用内存了。所以我不能够一次性解压缩了,只能分批解压。这个还算比较好处理,只要
Unity3D值Input Manager 转载自:
NGUI的Input输入框限制中文字节数问题 转载自:一般来说,昵称等用户输入的自定义数据都需要限制一下显示的长度。NGUI的INPUT输入框限制的是最大的char字符数,char字符数其实就是string的长
友情链接: 武汉网站建设