Applying the same animation to objects in a collection through a loop #104
-
Hey! I've been using your Asset for some time now, it really came in handy! I recently run into a problem when trying to loop through a list of objects in coroutine, in order to apply the same animation to all these objects except the last one. private IEnumerator DestroyObjects()
{
for (int i = 0; i < _objects.Count - 1; i++)
{
yield return Tween.Scale(
_objects[i].transform,
startValue: 1f,
endValue: 0f,
duration: 0.2f)
.OnComplete(() => Destroy(_objects[i]))
.ToYieldInstruction();
}
} The problem is that the animation is only applied to the first object in the list. All the others are simply destroyed when the specified |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey! I'm glad PrimeTween is helpful for you :) Hmm, I just copy-pasted your code and it works as expected: all objects except the last one are scaled down, then destroyed one by one. However, I was able to replicate a similar issue to what you're describing by removing the There are two ways how you can fix the issue. The first and dirty one is to copy the But a cleaned solution would be to use OnComplete() overload that accepts target as the first parameter, like so: for (int i = 0; i < _objects.Count - 1; i++) {
Tween.Scale(
_objects[i].transform,
startValue: 1f,
endValue: 0f,
duration: 0.2f)
.OnComplete(_objects[i], target => Destroy(target));
} But still, your code seems to work fine, and because all the animations play sequentially due to |
Beta Was this translation helpful? Give feedback.
Hey! I'm glad PrimeTween is helpful for you :)
Hmm, I just copy-pasted your code and it works as expected: all objects except the last one are scaled down, then destroyed one by one.
However, I was able to replicate a similar issue to what you're describing by removing the
yield return ToYieldInstruction()
part. In this case, all objects are scaled down, but only the last one is destroyed. This happens because thei
variable is captured in a closure inside the OnComplete() callback and its value is shared between all callbacks. The compiler also warns about this issue with the warning: "Captured variable is modified in the outer scope".There are two ways how you can fix the issue. The fi…