Unity RectTransform.SizeDelta 在Awake和Start输出为0

本文揭示了在Unity中使用VerticalLayout或HorizontalLayout配合ContentSizeFitter时,Awake和Start阶段SizeDelta值不准确的问题,建议在Update中获取稳定尺寸。更新前几帧也可能为0,务必检查后再用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当使用VerticalLayout或者HorizontalLayout或GridLayout这种布局结合ContentSizeFitter组件的时候,在Awake或Start生命周期函数里使用RectTransform.SizeDelta会得到x或y为0的结果,但是在Update是正确的。

所以最好不要在Awake和Start里用这个值。

补充:Update前几帧也会为0,最好还是得判断下是不是0,不是0 的时候再用这个值。

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class Canvas : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { RectTransform background, startArea, arrow, ball, basketry, target, trangle; Vector2 startPos, force, velocity, acceleration; bool isShoot; float left, bottom; Vector2 P1, P2; static readonly float MASS = 0.3f; static readonly Vector2 Gravity = new Vector2(0, -9.8f * 130 * MASS); static readonly float Height = 500; static readonly float Width = 640; static readonly float RadiusOfBall = 36; static readonly float LossRateOfCollide = 0.8f; // Start is called before the first frame update void Start() { left = -Width / 2; bottom = -Height / 2; Vector2 offset = -new Vector2(left, bottom); background = CreateSprite("background"); background.anchoredPosition = Vector2.zero; background.sizeDelta = new Vector2(Width, Height); startArea = CreateSprite("startArea"); startArea.anchoredPosition = new Vector2(80, 150) - offset; startArea.sizeDelta = new Vector2(100, 100); // To do: 使用CreateSprite函数加载指示发射方向的箭头, // 函数参数imageName是"arrow", // 函数返回值保存至变量arrow中, // 设置arrow,使之以背景左下角为坐标系原点时,位置是(80,150), // 尺寸是690x120 arrow = CreateSprite("arrow"); arrow.transform.SetParent(background); arrow.anchoredPosition = new Vector2(80, 150); arrow.sizeDelta= new Vector2(690, 120); arrow.localScale = Vector3.one * 0.1f; // To do: 加载篮球, // imageName是"ball", // 以背景左下角为坐标系原点时,位置是(80,150), // 尺寸是72x72 ball= CreateSprite("ball"); ball.position = new Vector2(80, 150); ball.sizeDelta = new Vector2(72, 72); // To do: 加载球篮(篮框), // imageName是"basketry", // 以背景左下角为坐标系原点时,位置是(550,300),
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mayikami

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值