if (leftAnchor.rect != null && leftAnchor.rect.mUpdateFrame != frame)
if (bottomAnchor.rect != null && bottomAnchor.rect.mUpdateFrame != frame)
从上面的方法可以看出,当锚点更新类型是OnUpdate时,会先调用目标的Update方法,如果自顶向下都有锚点且都是OnUpdate类型,就会一直递归至顶层开始顺序调用OnAnchor,而且每帧都会调用,这会很消耗cpu,非常蛋疼,所以在AnchorUpdate类型最好不要设置为OnUpdate ,应该设置为OnEnable,如下图:
如果锚点的目标也有锚点的话,比如A的锚点目标是B,B的锚点是C,如果存在这种多层锚点的情况,设置为OnEnable可能会有问题,所以尽量不要出现多层的情况.
部分代码:
//如果4个顶点绑定到同一个对象上
if (leftAnchor.target == bottomAnchor.target &&
leftAnchor.target == rightAnchor.target &&
leftAnchor.target == topAnchor.target)
{
//获得父对象相对于当前对象的4条边的位置,顺序是左,上,右,下
Vector3[] sides = leftAnchor.GetSides(parent);
if (sides != null)
{
// 左边位置 = 父对象左边位置 + 左边边距 (leftAnchor的relative为0,lerp运算得出结果是sides[0].x)
lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute;
// 右边位置 = 父对象右边位置 + 右边边距 (rightAnchor的relative为1,Lerp运算得出结果是sides[2].x)
rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute;
// 底部位置 = 父对象底部位置 + 底部边距 (bottomAnchor的relative为0,Lerp运算得出结果是sides[3].y)
bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute;
// 顶部位置 = 父对象顶部位置 + 顶部边距 (topAnchor的relative为1,Lerp运算得出结果是sides[1].y)
tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute;
}
}
//relative并不一定是固定的,如果如果目标的锚点位置设置为center的话,relative会设置为0.5
......
//计算新的位置,和大小
Vector3 newPos = new Vector3(Mathf.Lerp(lt, rt, pvt.x), Mathf.Lerp(bt, tt, pvt.y), pos.z);
int w = Mathf.FloorToInt(rt - lt + 0.5f);
int h = Mathf.FloorToInt(tt - bt + 0.5f);
cachedTransform.localPosition = newPos;
mWidth = w;
mHeight = h;
总结:当设置了锚点目标的时候,锚点对象就的空间属性就不仅由自己决定了,对象会通过父节点的位置和大小变化情况,而更新自己的位置和大小。Anchor类型最好设置为OnEnable,尽量不要出现多层锚点.