我需要知道如何将方法传递给类构造函数,以便以后可以调用它。这个想法是要创建一个Bullet类,它具有两个属性,一个损坏整数和一个当该类型的子弹击中一个对象时可以调用的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()
{
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句