DynamicLine.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityAsync;
  5. using System;
  6. using System.Threading;
  7. public class DynamicLine : MonoBehaviour
  8. {
  9. // Start is called before the first frame update
  10. public LineRenderer lineRenderer;
  11. public int splitNum = 60;
  12. public Action<int> OnTouchIndex;
  13. private CancellationTokenSource cancellationTokenSource; // 用于取消上一个任务
  14. private void Start()
  15. {
  16. lineRenderer = GetComponent<LineRenderer>();
  17. }
  18. public async void SetDynamicPoint(List<Vector3> pos)
  19. {
  20. // 如果有正在进行的操作,取消它
  21. if (cancellationTokenSource != null)
  22. {
  23. cancellationTokenSource.Cancel();
  24. }
  25. // 创建一个新的 CancellationTokenSource 用于新的操作
  26. cancellationTokenSource = new CancellationTokenSource();
  27. CancellationToken token = cancellationTokenSource.Token;
  28. if (pos.Count > 0)
  29. {
  30. int currentIndex = 0;
  31. await new UnityAsync.WaitForSeconds(1.0f);
  32. OnTouchIndex?.Invoke(currentIndex);
  33. // 遍历点,检查是否被取消
  34. for (currentIndex = 0; currentIndex < pos.Count - 1; currentIndex++)
  35. {
  36. lineRenderer.positionCount = currentIndex + 2;
  37. Vector3 startPos = pos[currentIndex];
  38. Vector3 endPos = pos[currentIndex + 1];
  39. Vector3 delta = endPos - startPos;
  40. Vector3 eachDelta = delta / splitNum;
  41. for (int i = 0; i < splitNum; i++)
  42. {
  43. // 检查是否取消了当前操作
  44. if (token.IsCancellationRequested)
  45. {
  46. return; // 取消操作,退出方法
  47. }
  48. lineRenderer.SetPosition(currentIndex, startPos);
  49. lineRenderer.SetPosition(currentIndex + 1, startPos + eachDelta * i);
  50. await new WaitForEndOfFrame();
  51. await new WaitForEndOfFrame();
  52. await new WaitForEndOfFrame();
  53. await new WaitForEndOfFrame();
  54. await new WaitForEndOfFrame();
  55. }
  56. OnTouchIndex?.Invoke(currentIndex + 1);
  57. }
  58. }
  59. }
  60. }