Unity协同程序

延迟函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent<PlayerController>(out PlayerController player))
{
collider.enabled = false;
// 延迟3秒
// Invoke("Reset", time: 3f);
Invoke(methodName: nameof(Reset), time: 3f);

// 延迟3秒,每2秒调用一次Reset函数
// InvokeRepeating(methodName: nameof(Reset), time: 3f, repeatRate: 2f);

// 取消延迟调用
// CancelInvoke(nameof(Reset));
}
}
void Reset()
{
collider.enabled = true;
}

协同程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System.Collections;
using UnityEngine;

public class SomeThing : MonoBehaviour
{
new Collider2D collider;

WaitForSeconds waitResetTime;

private void Awake()
{
collider = GetComponent<Collider2D>();

waitResetTime = new WaitForSeconds(3f);
}

private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent<PlayerController>(out PlayerController player))
{
collider.enabled = false;
StartCoroutine(ResetCoroutine());
}
}

void Reset()
{
collider.enabled = true;
}

IEnumerator ResetCoroutine()
{
yield return waitResetTime;
Reset();
}
}

可关闭之前的协同程序,重新调用

1
2
3
4
5
6
7
8
9
10
11
12
13
public void SetJumpInputBufferTimer()
{
StopCoroutine(nameof(JumpInputBufferCoroutine));
StartCoroutine(nameof(JumpInputBufferCoroutine));
}

IEnumerator JumpInputBufferCoroutine()
{
HasJumpInputBuffer = true;
yield return waitJumpInputBufferTime;

HasJumpInputBuffer = false;
}

Unity协同程序
http://example.com/2025/06/18/unity-coroutine/
作者
dsaco
发布于
2025年6月18日
许可协议