12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityAsync;
- using System;
- using System.Threading;
- public class DynamicLine : MonoBehaviour
- {
- // Start is called before the first frame update
- public LineRenderer lineRenderer;
- public int splitNum = 60;
- public Action<int> OnTouchIndex;
- private CancellationTokenSource cancellationTokenSource; // 用于取消上一个任务
- private void Start()
- {
- lineRenderer = GetComponent<LineRenderer>();
- }
- public async void SetDynamicPoint(List<Vector3> pos)
- {
- // 如果有正在进行的操作,取消它
- if (cancellationTokenSource != null)
- {
- cancellationTokenSource.Cancel();
- }
- // 创建一个新的 CancellationTokenSource 用于新的操作
- cancellationTokenSource = new CancellationTokenSource();
- CancellationToken token = cancellationTokenSource.Token;
- if (pos.Count > 0)
- {
- int currentIndex = 0;
- await new UnityAsync.WaitForSeconds(1.0f);
- OnTouchIndex?.Invoke(currentIndex);
- // 遍历点,检查是否被取消
- for (currentIndex = 0; currentIndex < pos.Count - 1; currentIndex++)
- {
- lineRenderer.positionCount = currentIndex + 2;
- Vector3 startPos = pos[currentIndex];
- Vector3 endPos = pos[currentIndex + 1];
- Vector3 delta = endPos - startPos;
- Vector3 eachDelta = delta / splitNum;
- for (int i = 0; i < splitNum; i++)
- {
- // 检查是否取消了当前操作
- if (token.IsCancellationRequested)
- {
- return; // 取消操作,退出方法
- }
- lineRenderer.SetPosition(currentIndex, startPos);
- lineRenderer.SetPosition(currentIndex + 1, startPos + eachDelta * i);
- await new WaitForEndOfFrame();
- await new WaitForEndOfFrame();
- await new WaitForEndOfFrame();
- await new WaitForEndOfFrame();
- await new WaitForEndOfFrame();
- }
- OnTouchIndex?.Invoke(currentIndex + 1);
- }
- }
- }
- }
|