延迟调用方法 Invoke

目前正跟随官网 Junior Programmer 课程学习。

前一段时间学习到的一些内容,将分别纪要。

1.延迟调用

使用:

1
Invoke (string methodName, float time);

来延迟调用某个方法。

其描述为:

1.1描述

time 秒后调用 methodName 方法。

如果时间设置为 0,则在下一个更新周期调用方法。在这种情况下,直接调用函数会更好。

为获得更好的性能和可维护性,请改为使用协程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using UnityEngine;
using System.Collections.Generic;public class ExampleScript : MonoBehaviour
{
// 2秒后调用 LaunchProjectile
Rigidbody projectile;
void Start()
{
Invoke("LaunchProjectile", 2.0f);
}

void LaunchProjectile()
{
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5.0f;
}
}

以上。

2.延迟-重复调用

使用:

1
InvokeRepeating (string methodName, float time, float repeatRate);

来延迟并重复调用某个方法。

其描述为:

2.1描述

time 秒后调用 methodName 方法,然后每 repeatRate 秒调用一次。

注意:如果将时间刻度设置为 0,该函数不起作用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using UnityEngine;
using System.Collections.Generic;

// 2秒后开始调用 LaunchProjectile
// 此后每0.3秒调用一次 LaunchProjectile
public class ExampleScript : MonoBehaviour
{
public Rigidbody projectile;

void Start()
{
InvokeRepeating("LaunchProjectile", 2.0f, 0.3f);
}

void LaunchProjectile()
{
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
}

以上。

上述描述来源于 Unity Document,以下路径:

以上。