赞
踩
UGUI获取RectTransform的某些属性时坑实在是太多了,以博主踩过的坑记录一下:
参考宣雨松大神的做法:Unity3D研究院之ContentSizeFitter同步立即响应回调
public static Vector2 GetPreferredSize (RectTransform rect, ContentSizeFitter fitter) { if (rect == null || fitter == null) { return Vector2.zero; } LayoutRebuilder.ForceRebuildLayoutImmediate (rect); return new Vector2 (HandleSelfFittingAlongAxis (0, fitter, rect), HandleSelfFittingAlongAxis (1, fitter, rect)); } //获取宽和高 private static float HandleSelfFittingAlongAxis (int axis, ContentSizeFitter fitter, RectTransform rect) { ContentSizeFitter.FitMode fitting = (axis == 0 ? fitter.horizontalFit : fitter.verticalFit); if (fitting == ContentSizeFitter.FitMode.MinSize) { var size = LayoutUtility.GetMinSize (rect, axis); return size; } else { var size = LayoutUtility.GetPreferredSize (rect, axis); return size; } }
如果想获取Canvas的RectTransform.rect.width / RectTransform.rect.height出现这个提示时要小心了,rect很有可能宽高都是零,估计也是因为RectTransform需要等一帧才会把正确的宽高设置到RectTransform中,因此博主的做法是:
开一个协程,不断检测RectTransform.rect.width / RectTransform.rect.height,当两个值都大于零才执行你的回调
注意,如果有需求把物体的世界坐标转换到某个Canvas下的UI坐标时,也要等到Canvas的rect宽高都大于零,否则也是错的,这里提供一下转换的代码:
public static Vector3 WorldToUGUIPosition (Camera worldCam, Vector3 worldPos, Camera uiCamera, RectTransform uiRect) {
var pos = worldCam.WorldToScreenPoint (worldPos);
Vector2 result;
RectTransformUtility.ScreenPointToLocalPointInRectangle(uiRect, pos, uiCamera, out result);
return result;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。