Home > front end >  How to implement async in DOTween?
How to implement async in DOTween?

Time:05-30

I'm working on an animation that pops up a popup screen using DOTween.

private void OnEnable()
{
  dialogueBoxTransform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
  dialogueBoxTransform.DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.2f);
  dialogueBoxTransform.DOScale(Vector3.one, 0.1f);
}

The problem with the code above is that one of the DOScale() methods is ignored.

So I'm trying to implement it using async-await.

However, when I use Task.Run() it throws an exception because it is not the main thread. So, without using Task.Run(), you should solve it.

To do that, I need to create a method that returns a Task, but I don't know how.

private async void OnEnable()
{
  dialogueBoxTransform.localScale = new Vector3(0.7f, 0.7f, 0.7f);

  await Test();
      
  dialogueBoxTransform.DOScale(Vector3.one, 0.1f);
}

private Task Test()
{
  dialogueBoxTransform.DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.2f);
  return ???
}

I would appreciate any help on what to do.

CodePudding user response:

As @rbcode has mentioned, you should use Sequence. It's a powerful tool that allows you to combine tweens, add callbacks, etc.

In your case it should look like this:

dialogueBoxTransform.localScale = new Vector3(0.7f, 0.7f, 0.7f);

var sequence = DOTween.Sequence();
sequence.Append(dialogueBoxTransform.DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.2f));
sequence.Append(dialogueBoxTransform.DOScale(Vector3.one, 0.1f));

sequence.Play();

If you want to execute code after the sequence is completed, you can add a callback before calling Play:

sequence.AppendCallback(() => {
   //Insert your logic here.
});

sequence.Play();

CodePudding user response:

Use the sequence feature of DOTween. The second DOScale-command is ignored, because the first one is not finished yet.

  • Related