ButtonShaker.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System.Threading.Tasks;
  2. using UnityEngine.UIElements;
  3. namespace Edgegap.Editor
  4. {
  5. /// <summary>Slightly shake a UI button to indicate attention.</summary>
  6. public class ButtonShaker
  7. {
  8. const string SHAKE_START_CLASS = "shakeStart";
  9. const string SHAKE_STOP_CLASS = "shakeEnd";
  10. private Button targetButton;
  11. public ButtonShaker(Button buttonToShake) =>
  12. targetButton = buttonToShake;
  13. /// <summary>Shake the button x times for x msDelayBetweenShakes each.
  14. /// 1 shake = 1 bigger -> followed by 1 smaller.</summary>
  15. /// <param name="msDelayBetweenShakes"></param>
  16. /// <param name="iterations"># of shakes</param>
  17. public async Task ApplyShakeAsync(int msDelayBetweenShakes = 40, int iterations = 2)
  18. {
  19. for (int i = 0; i < iterations; i++)
  20. await shakeOnce(msDelayBetweenShakes);
  21. }
  22. private async Task shakeOnce(int msDelayBetweenShakes)
  23. {
  24. targetButton.AddToClassList(SHAKE_START_CLASS);
  25. await Task.Delay(msDelayBetweenShakes); // duration of the first transition
  26. targetButton.RemoveFromClassList(SHAKE_START_CLASS);
  27. targetButton.AddToClassList(SHAKE_STOP_CLASS);
  28. await Task.Delay(msDelayBetweenShakes); // duration of the second transition
  29. targetButton.RemoveFromClassList(SHAKE_STOP_CLASS);
  30. }
  31. }
  32. }