Delegate 让你的函数更专向

Posted on 2012-12-31 10:24  neocsl  阅读(226)  评论(0编辑  收藏  举报
function Touch(Actor Other,PrimitiveComponent OtherComp,Vector HitLocation,vector HitNormal)
{   
      OnTouch(self,Other,OtherComp,HitLocation,HitNormal);
}

simulated delegate OnTouch(Actor Caller,Actor Other,PrimitiveComponent OtherComp,vector HitLocation,vector HitNormal);

 

  代理Delegate可以使一个方法在不同的类中有不同的反馈方法。例如Trigger的Touch函数和炮塔,机器人,生物敌人。

Delegate可以让你的类定义包含的变量类的内部方法。这句话听起来有些拗口;) 没关系,示例是你的好老师。我要声明一个Trigger类,这个类可以在别人接触他的时候触发事件,例如炮塔可以用它划定自己的攻击触发事件。机器人也可以用它触发自己的事件。

  在自定义的Trigger中,你首先实现它的两个常规函数Touch和UnTouch。但是具体怎么实现的时候使用Delegate函数。

  然后再AntTower中使用该类

class AntTower extends pawn placeable;

var AntTrigger DetectiveSight;

simulated function PostBeginPlay()
{
     super.PostBeginPlay();
     
     DetectiveSight=Spawn(class'AntTrigger',,,location);

   if(DetectiveSight!=none)
{
//这里非常重要,实现Delegate函数的地方
DetectiveSight.OnTouch=InternalOnTouch;
      }
}

   代理类自身的销毁也非常重要,关系到垃圾处理。优化一款游戏应该谨慎垃圾回收。

simulated event Destroyed()
{
     super.Destroyed();
   
     if(DetectiveSight!=none)
    {
          DetectiveSight.OnTouch=none;
          DetectiveSight.Destroy();
    }
}

  最后实现自己代理的函数

function IntervalOnTouch(Actor Caller,PrimitiveComponent OtherCOmp,vector HitLocation,vector HitNormal)
{
    //...
}