using UnityEngine;
using UnityEngine.Events;
public class random : MonoBehaviour
{
//声明带参委托
public UnityAction<string> aaa;
//声明带参带返回值委托
public System.Func<int, int, int> bbb;
public void Attack(string bossname)
{
print("打击怪兽:" + bossname);
}
public int addfunc(int a, int b)
{
return a + b;
}
public int addfunc2(int a, int b)
{
return a + b;
}
// Start is called before the first frame update
void Start()
{
aaa=Attack;
aaa("怪兽");
bbb = addfunc;
int c= bbb(1, 2);
print(c); //3
bbb += addfunc2;
c = bbb(3, 4);
print(c); //7
//C#的委托
System.Action ac = () =>
{
print("C#无参无返回值委托");
};
System.Action<int, float> ac2 = (a, b) => {
print("C#有参无返回值委托");
};
System.Func<int> fun1 = () => {
print("C#无参带返回值委托");
return 1;
};
//多个参数,最后一个是返回值
System.Func<int, int, int> fun2 = (a,b) => {
return a+b;
};
//调用
ac();
ac2(1, 2);
print("fun:" + fun1());
print("fun:" + fun2(3,5));
//Unity自带委托
//无参无返回值的委托
UnityAction uac = () =>
{
print("Unity无参委托");
};
//无返回值带参数的委托
UnityAction<string,int> uac2 = (s,a) =>
{
print(s+","+a.ToString());
};
uac();
uac2("haha",2);
//总结:如果需要返回值的委托,就用C#的带返回值的委托
//?.就是有内容就执行,没有就不执行
bbb?.Invoke(1,1);
print("bbb里没放容器");
print("------------------");
bbb = addfunc;
int c= bbb(1, 2);
print("bbb里有容器:" + c);
}
}