Unity之Invoke

Invoke 是 MonoBehaviour 类中的方法,用于延迟调用方法。

1、基本用法

Invoke()
cs 复制代码
// 基本语法
Invoke("方法名", 延迟时间);

// 示例
void Start()
{
    // 3秒后执行 Shoot 方法
    Invoke("Shoot", 3f);
}

void Shoot()
{
    Debug.Log("射击!");
}
InvokeRepeating()
cs 复制代码
// 基本语法
InvokeRepeating("方法名", 首次延迟时间, 重复间隔时间);

// 示例
void Start()
{
    // 2秒后第一次执行,之后每隔1秒重复执行
    InvokeRepeating("SpawnEnemy", 2f, 1f);
}

void SpawnEnemy()
{
    Debug.Log("生成敌人!");
}
CancelInvoke()
cs 复制代码
// 停止所有通过 Invoke 调用的方法
CancelInvoke();

// 停止特定方法
CancelInvoke("方法名");
IsInvoking()
cs 复制代码
// 检查是否有任何 Invoke 正在执行
if (IsInvoking())
{
    // 有方法正在等待执行
}

// 检查特定方法是否正在等待执行
if (IsInvoking("方法名"))
{
    // 该方法正在等待执行
}

2、Invoke与委托结合使用

从 Unity 2017.1 开始,可以使用 Action 委托替代字符串方法名:

cs 复制代码
// 使用 Invoke 的替代方案
void Start()
{
    // 延迟执行
    StartCoroutine(DelayedAction(2f, () => 
    {
        Debug.Log("延迟执行");
    }));
    
    // 重复执行
    StartCoroutine(RepeatingAction(1f, 0.5f, () => 
    {
        Debug.Log("重复执行");
    }));
}

IEnumerator DelayedAction(float delay, Action action)
{
    yield return new WaitForSeconds(delay);
    action?.Invoke();
}

IEnumerator RepeatingAction(float startDelay, float interval, Action action)
{
    yield return new WaitForSeconds(startDelay);
    
    while (true)
    {
        action?.Invoke();
        yield return new WaitForSeconds(interval);
    }
}

与自定义委托结合

cs 复制代码
    public delegate void DelegateTest();
    class Program
    {
        static void Main(string[] args)
        {
            DelegateTest dele = new DelegateTest(Test1);
            dele += Test2;
            // 执行
            //dele();  // 简化语法
            dele.Invoke();

        }
        static void Test1()
        {
            Console.WriteLine("Test1");
        }
        static void Test2()
        {
            Console.WriteLine("Test2");
        }
    }

3、最佳实践和注意事项

  1. 性能考虑:
  • 避免频繁使用 Invoke,特别是在 Update 中
  • 对于性能敏感的场景,优先使用协程
  1. 代码维护:
  • 字符串方法名容易拼写错误,且重构时不安全
  • 考虑使用委托或协程替代
  1. 对象销毁时:
  • GameObject 被销毁时,所有 Invoke 调用会自动取消
  • 脚本被禁用时,Invoke 不会自动停止
  1. 精度问题:
  • Invoke 的时间精度不如 Time.deltaTime 精确
  • 对于需要精确时间控制的场景,建议使用 Update 配合计时器
相关推荐
xcLeigh12 小时前
Unity基础:Instantiate实例化——在运行时动态创建游戏物体
游戏·unity·游戏引擎·教程·instantiate
流浪打工人1 天前
Unity3d TimeLine中audio track的使用
unity
淡海水1 天前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
WarPigs1 天前
UI路径配置SO>字典json工作流
ui·unity
淡海水2 天前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
阿松爱学习2 天前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
淡海水2 天前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots
辻弋2016 天前
五年前的旅行视频糊成马赛克?Video2X用Real-ESRGAN逐帧重建细节,但只支持Windows、集显用户建议直接放弃
服务器·数据库·windows·游戏引擎·电脑
Martina_03217 天前
AI生成3D场景导入 Unity/Unreal 后,NPC 总串层?用6步检查导航高度与跨层连接
人工智能·游戏·数学建模·3d·unity·自然语言处理·aigc
小贺儿开发7 天前
Unity 局域网遥控幻灯片展示工具 3.0
科技·http·unity·工具·ppt·通信·网页