如何将方法保存在稍后执行的类中
本文关键字:执行 存在 方法 保存 | 更新日期: 2023-09-27 18:03:45
我需要知道如何将方法传递给类构造函数,以便以后调用它。我们的想法是有一个Bullet类,它有两个属性,一个是damage整数,一个是Method,当这种类型的子弹击中一个对象时可以调用这个Method。下面的代码应该能更好地解释:
public class Bullet
{
public Method OnHit;
public int Damage;
public Bullet(int Damage,Method OnHit)
{
this.Damage = Damage;
this.OnHit = OnHit;
}
}
这样我就可以通过运行像Bullet.OnHit(HitGameObject)这样的东西让子弹在撞击时执行不同的任务。
您可以使用Action
将函数传递给函数,然后将其存储在另一个Action
中。存储的函数可以用Action.Invoke()
调用
public class Bullet
{
public int Damage;
System.Action savedFunc;
public Bullet(int Damage, System.Action OnHit)
{
if (OnHit == null)
{
throw new ArgumentNullException("OnHit");
}
this.Damage = Damage;
savedFunc = OnHit;
}
//Somewhere in your Bullet script when bullet damage == Damage
void yourLogicalCode()
{
int someBulletDamage = 30;
if (someBulletDamage == Damage)
{
//Call the function
savedFunc.Invoke();
}
}
}
使用:
void Start()
{
Bullet bullet = new Bullet(30, myCallBackMethod);
}
void myCallBackMethod()
{
}
你需要的是c#中的委托,首先,你应该定义方法输入/输出,然后像使用变量一样使用这种类型的方法。
public class Bullet
{
public delegate void OnHit(bool something);
public OnHit onHitMethod;
public int Damage;
public Bullet(int Damage, OnHit OnHit)
{
this.Damage = Damage;
this.onHitMethod = OnHit;
}
}
在这行public delegate void OnHit(bool something);
中,您只是定义了委托的类型,在这行public OnHit onHitMethod;
中,您定义了方法,就像变量一样。