How does PrimeTween use structs to track and control ReuseableTweens? #201
-
|
Been trying to figure out the inner works of this package, and what I cant seem to wrap my head around is the usage of structs that track ReuseableTweens. Since structs are a value type, they return a copy which wouldnt seem to be able to track whether the object was freed back into the pool and being used by something else, but PrimeTween seems to make it happen. How does this work? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
That's a great question and actually a fundamental part of PrimeTween :) As you correctly pointed out, returning ReusableTween reference to the user is not an option. Because if a user saves the reference and ReusableTween is reused for another animation, the stored reference would point to a wrong animation. Interestingly enough, DOTween behaves like this with "Reuse tweens" option, which makes it very error prone to use. PrimeTween solves it by storing a unique id inside the public struct Tween {
long id;
ReusableTween tween;
public bool isAlive => id != 0 && tween.id == id && tween._isAlive;
public void Complete() {
if (isAlive) {
// ...
}
}
}This design allows the Tween struct to be safely cached, copied, or passed as parameter to functions. While making sure it always refers to the correct ReusableTween and preventing memory allocations. |
Beta Was this translation helpful? Give feedback.
That's a great question and actually a fundamental part of PrimeTween :)
As you correctly pointed out, returning ReusableTween reference to the user is not an option. Because if a user saves the reference and ReusableTween is reused for another animation, the stored reference would point to a wrong animation. Interestingly enough, DOTween behaves like this with "Reuse tweens" option, which makes it very error prone to use.
PrimeTween solves it by storing a unique id inside the
Tweenstruct along with aReusableTween tweenreference. TheTweenis then consideredisAlivewhen itsid == tween.idand each public API is guarded with thisisAlivecheck: