Unity中Invoke和BeginInvoke的使用--新手小白的一些简单看法
Unity新手对Invoke和BeginInvoke的一些看法,欢迎大佬指点
Invoke方法可以用来发布事件,可以使用带返回值的委托类型实现同步回调
BeginInvoke方法是异步回调函数,其参数为BeginInvoke(委托参数,回调函数,回调函数的参数)
回调函数的参数必须为IAsyncResult类型。
回调函数的参数是object类型。
BeginInvoke方法不能同时发布给两个或两个以上的观察者
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ddelegate : MonoBehaviour
{
//创建委托
public delegate void BossHp(int hp);
//创建事件
public event BossHp BossHpEvent;
//创建一个带返回值的委托
public delegate string BossHpWithReturn(int hp);
public event BossHpWithReturn BossHpWithReturnEvent;
public static Ddelegate instance;
private void Awake()
{
instance = this;
}
private void Start()
{
//同步调用
print( BossHpWithReturnEvent.Invoke(50));
Debug.Log("同步回调成功");
//异步回调
BossHpEvent.BeginInvoke(70, AsyncInvoke, "no");
Debug.Log("异步回调成功");
}
private void AsyncInvoke(IAsyncResult ar)
{
Debug.Log(ar.AsyncState);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventText : MonoBehaviour
{
void Start()
{
Ddelegate.instance.BossHpEvent += BossHp;
Ddelegate.instance.BossHpWithReturnEvent += BossHpWithReturn;
}
// Update is called once per frame
public void BossHp(int hp)
{
Debug.Log(hp);
}
private string BossHpWithReturn(int hp)
{
Debug.Log(hp + 20);
return "yes";
}
}