NGUI源码剖析之UIRect

UIRect是一个代表UI矩形区的抽象类。一个矩形区有上、下、左、右四边,因此UIRect中有4个锚点分别指示这四边anchor的位置:
public AnchorPoint leftAnchor = new AnchorPoint();
public AnchorPoint rightAnchor = new AnchorPoint(1f);
public AnchorPoint bottomAnchor = new AnchorPoint();
public AnchorPoint topAnchor = new AnchorPoint(1f);

有bottom-left、top-left、top-right、bottom-right四个角:
public abstract Vector3[] localCorners { get; }
public abstract Vector3[] worldCorners { get; }

每个矩形区是一个UI的容器,因此UIRect可以组成一个树状结构:
BetterList<UIRect> mChildren即孩子节点列表,OnInit、OnDisable及ParentHasChanged时将进行动态的Add和Remove。
UIRect mParent即父节点,会从该UIRect绑定的GameObject进行回溯寻找,bool mParentFound表示其有没有进行过回溯寻找。

NGUI中UIRoot是所有UI对象的根节点,UIRect中的UIRoot mRoot就指向了该节点,bool mRootSet表示其有没有进行过回溯寻找。

UIRect里为了加速访问绑定的GameObject及其Transform做了缓存:
protected GameObject mGo;
protected Transform mTrans;
public GameObject cachedGameObject { get { if (mGo == null) mGo = gameObject; return mGo; } }
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }

Camera mMyCam为负责渲染UIRect绑定的GameObject这一层的Camera,bool mAnchorsCached表示其以及4个锚点的数据有没有设置好。
bool mStarted:UnityEngine是否回调了Start方法
bool mChanged:父对象中有值(如alpha)改变时将其设置为true,用于刷新表现。
int mLastInvalidate:通过Time.frameCount记录下最后调用Invalidate的帧数。
int mUpdateFrame:通过Time.frameCount记录已经Update过的帧数。

UIRect中的主要功能在Update里:
1、通过mAnchorsCached判断是否需要更新锚点的相关数据,需要则通过ResetAnchors来更新数据。
2、通过mUpdateFrame与Time.frameCount判断该帧是否已经经过Update处理,处理过则本次Update结束了。
3、分别判断4个锚点是否有设置,有的话则判断该锚点的rect是否已经经过Update处理,未处理过则调用其Update方法。
4、判断4个锚点是否至少有1个有设置,则调用OnAnchor方法。
5、调用OnUpdate方法继续处理。
OnAnchor和OnUpdate方法均是抽象方法,需要由UIRect的子类自己来实现:
protected abstract void OnAnchor ();
protected virtual void OnUpdate () { }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据