Unity 笔记

获取子节点

使用 GetComponentsInChildren 会返回自身以及子节点,如果要排除自身可以使用以下方法

// transform 本身是可迭代类型,直接迭代即可获取子节点元素
foreach (Transform t in transform) {}

// 使用 Linq 对列表处理
GetComponentsInChildren<Transform>().Where(t => t != transform)
// or
GetComponentsInChildren<Transform>().Skip(1)

常用旋转方法

旋转 vector,使用 Quaternion * Vector3 得到旋转后的 vector

// 将 forward 绕 Y 轴旋转 45
Quaternion.Euler(0, 45, 0) * transform.forward
// 或者使用 AngleAxis 构建 rotation 结果一样
Quaternion.AngleAxis(45, Vector3.up) * vector;

由 vector 得到 rotation

// 得到 fromVector 到 toVector 的 rotation
Quaternion FromToRotation(Vector3 fromVector, Vector3 toVector)
// 将目标 forward 向量对齐到 newForward 向量的 rotation
Quaternion LookRotation(Vector3 newForward)

叠加两个 rotation,使用 Quaternion * Quaternion

// 每帧旋转角度
float angle = rotateSpeed * Time.deltaTime;
// 将右边的 rotation 叠加到第一 rotation
transform.rotation = transform.rotation * Quaternion.AngleAxis(angle, Vector3.up);

Event 使用注意

UnityAction, Action 未订阅直接调用会报错

// 使用时需要判断空
onClickDown?.Invoke()

UnityEvent 直接调用不会报错,对 UnityEvent 判断空无效

// 判断空是无效的
// 可以使用 GetPersistentEventCount 判断通过编辑添加的
// 但代码中通过 AddListener 添加的并不计入
if(onClickDown.GetPersistentEventCount() > 0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值