Unity Dotween在Update中的正确使用

前言

想在Update中直接使用Dotween进行缓动,而不是写插值计算缓动。

直接写法

this.transform.DOMove(targetPos, 0.1f);

这种写法是可以实现效果的,但是会发现Dotween给了一个警告:

在这里插入图片描述
这个警告的意思是,Tween数达到最大值,容量自动增加。
出现原因则是因为Dotween每次调用都会产生一个Tween对象。因此这样会导致创建大量的Tween对象,对性能产生影响。

正确写法

private Tweener _tweener;

void Start{
    
    
	_tweener = this.transform.DOMove(targetPos, 0.1f).SetAutoKill(false); 
}

void Update(){
    
    
	// 给定pos并play
	_tweener.ChangeEndValue(targetPos, true).Play();
}

ChangeEndValue的官方说明

ChangeEndValue(newEndValue, float duration = -1, bool snapStartValue = false)
Changes the end value of a Tweener and rewinds it (without pausing it).
更改 Tweener 的结束值并倒带(不暂停)。
Has no effect with Tweeners that are inside Sequences.
对序列内部的 Tweener 没有影响。
NOTE: works on regular tweens, not on ones that do more than just animate one value from one point to another (like DOLookAt).
注意:适用于常规补间,不适用于那些不仅仅是将一个值从一点动画化到另一点(如 DOLookAt )的补间。
NOTE: for shortcuts that accept a single axis (DOMoveX/Y/Z, DOScaleX/YZ, etc) you still have to pass a full Vector2/3/4 value, even if only the one you set in the tween will be considered.
注意:对于接受单轴(DOMoveX/Y/Z、DOScaleX/YZ 等)的快捷方式,您仍然必须传递完整的 Vector2/3/4 值,即使只考虑您在补间中设置的值。
newEndValue: New end value. 新的结束值。
duration: If bigger than 0 also changes the duration of the tween.
如果大于 0 也会更改补间的持续时间。
snapStartValue: If TRUE the start value will become the current target’s value, otherwise it will stay the same.
如果为 TRUE,起始值将成为当前目标的值,否则它将保持不变。

这个API用于更新一个已存在的Tween的结束值,也就不需要创建新的Tween,从而解决了以上问题。
至于snapStartValue这个参数,找到的解释是

ChangeEndValue方法的snapStartValue参数用于确定Tween是否在更改结束值后立即将起始值跳转到新的结束值。
当snapStartValue设置为true时,Tween会立即将起始值跳转到新的结束值,从而在更改结束值后立即开始动画。这会导致一个突变的效果,跳过原始的起始值到达新的结束值。
当snapStartValue设置为false时,Tween会平滑地从当前的起始值过渡到新的结束值。这种过渡可以通过设置Tween的持续时间来控制。

猜你喜欢

转载自blog.csdn.net/RainWind777/article/details/130747999
今日推荐