学习lua结合unity

来源:互联网 发布:37轩辕剑骑兵进阶数据 编辑:程序博客网 时间:2024/05/22 15:21

 /////////////////////////////////////////////////////////////////////////////////////

else if(eventType == TrainOrderEvent.OpenTrainStation)
{
if (DataManager.Instance.Mode != GameMode.Self) return;
            UIModule.Instance.GetWindow(WindowName.TrainStationPanel).Open(TrainOrderProxy.Automatic.GetTrainOrderInfoByBoardId(OrderBoardType.normal_train_board_id),
  TrainOrderProxy.Automatic.GetTrainOrderInfoByBoardId(OrderBoardType.luxury_train_board_id));
            TrainOrderInfo normalInfo = TrainOrderProxy.Automatic.GetTrainOrderInfoByBoardId(OrderBoardType.normal_train_board_id);
            TrainOrderInfo luxuryInfo = TrainOrderProxy.Automatic.GetTrainOrderInfoByBoardId(OrderBoardType.luxury_train_board_id);
            
            if (!normalInfo.isEmpty) 
   {
       var data = normalInfo.data;
                if (data.leftTime < ServerTime.sInstance.ServerSecond )
                {
                    Debug.LogWarning("OpenTrainStation : IsRewardBack: " + (data.rewardBackTime <= ServerTime.sInstance.ServerSecond) + " , completedCabinCount>0: " + (data.completedCabin.Count > 0) + " ,rewardCabinCount > claimedRewardCount : " + (data.rewardCabin.Count > data.claimedReward.Count));
                    if (data.rewardBackTime <= ServerTime.sInstance.ServerSecond )
                    {
                        if (data.completedCabin.Count > 0)
                        {
                            if (data.rewardCabin.Count > data.claimedReward.Count)
                                UIModule.Instance.CallInterface(WindowName.TrainStationPanel, "OnlyNormalFresh", normalInfo);
                            else
                                FlushTrainNormalOrder();
                        }
                        else
                            FlushTrainNormalOrder();
                    }
                }
                CheckTrainTimers(normalInfo);
       InitTrainState(normalInfo, normalInfo.board.orderBoardId);
            }
            
   if (!luxuryInfo.isEmpty)
   {
       var data = luxuryInfo.data;
       if (data.leftTime < ServerTime.sInstance.ServerSecond)
       {
           if (data.rewardBackTime <= ServerTime.sInstance.ServerSecond)
           {
                        if (data.completedCabin.Count > 0)
                        {
                            if (data.rewardCabin.Count > data.claimedReward.Count)
                                UIModule.Instance.CallInterface(WindowName.TrainStationPanel, "OnlyLuxuryFresh", luxuryInfo);
                            else
                                FlushTrainLuxuryOrder();
                        }
                        else
                            FlushTrainLuxuryOrder();
                    }
       }
                CheckTrainTimers(luxuryInfo);
                InitTrainState(luxuryInfo, luxuryInfo.board.orderBoardId);
            }
            bool bVis = !normalInfo.isEmpty && normalInfo.carbinInfo.Find(i => i.isOk) != null || !luxuryInfo.isEmpty && luxuryInfo.carbinInfo.Find(i => i.isOk) != null;
            Messenger.Broadcast(TrainOrderEvent.TrainButtonRedHint, bVis);
        }


xlua.private_accessible(CS.TrainOrderHandler)
xutil.hotfix_ex(CS.TrainOrderHandler, 'handler', function (self,eventType,param)
if eventType == CS.TrainOrderEvent.OpenTrainStation then
Debug.LogError("-----------lua ----OpenTrainStation-----")
if CS.DataManager.Instance.Mode ~= CS.GameMode.Self then
return
end
--local openParam = {}
local normalInfo = CS.TrainOrderProxy.Automatic:GetTrainOrderInfoByBoardId(CS.OrderBoardType.normal_train_board_id)
            local luxuryInfo = CS.TrainOrderProxy.Automatic:GetTrainOrderInfoByBoardId(CS.OrderBoardType.luxury_train_board_id)
--table.insert(openParam, normalInfo)
--table.insert(openParam, luxuryInfo)

--for k, v in pairs(openParam) do
-- print("----------------" ,k , v)
--end

local window = CS.JunEngine.UI.UIModule.Instance:GetWindow(CS.WindowName.TrainStationPanel) 
window:Open(normalInfo, luxuryInfo)
print("----------------" ,normalInfo.isEmpty)
if normalInfo.isEmpty == false then
local data = normalInfo.data
if data.leftTime < CS.ServerTime.sInstance.ServerSecond then
if data.rewardBackTime <= CS.ServerTime.sInstance.ServerSecond then
if data.completedCabin.Count > 0 then
if data.rewardCabin.Count > data.claimedReward.Count then
local mPara = {}
table.insert(mPara, normalInfo)
                                CS.JunEngine.UI.UIModule.Instance:CallInterface(CS.WindowName.TrainStationPanel, "OnlyNormalFresh", mPara)
                            else
                                if CS.TrainOrderProxy.Instance.CanNormalFlush then
                                    CS.TrainOrderProxy.Instance.CanNormalFlush = false
                                    self:FlushTrainNormalOrder()
                                end
                            end
else
if CS.TrainOrderProxy.Instance.CanNormalFlush then
                                CS.TrainOrderProxy.Instance.CanNormalFlush = false
                                self:FlushTrainNormalOrder()
                            end
end
end
end
self:CheckTrainTimers(normalInfo)
       self:InitTrainState(normalInfo, normalInfo.board.orderBoardId)
end
if luxuryInfo.isEmpty == false then
local data = luxuryInfo.data
if data.leftTime < CS.ServerTime.sInstance.ServerSecond then
if data.rewardBackTime <= CS.ServerTime.sInstance.ServerSecond then
if data.completedCabin.Count > 0 then
if data.rewardCabin.Count > data.claimedReward.Count then
local mPara = {}
table.insert(mPara, luxuryInfo)
                                CS.JunEngine.UI.UIModule.Instance:CallInterface(CS.WindowName.TrainStationPanel, "OnlyLuxuryFresh", mPara)
                            else
                                if CS.TrainOrderProxy.Instance.CanLuxuryFlush then
                                    CS.TrainOrderProxy.Instance.CanLuxuryFlush = false
                                    self:FlushTrainLuxuryOrder()
                                end
                            end
else
if CS.TrainOrderProxy.Instance.CanLuxuryFlush then
                                CS.TrainOrderProxy.Instance.CanLuxuryFlush = false
                                self:FlushTrainLuxuryOrder()
                            end
end
end
end
self:CheckTrainTimers(luxuryInfo)
       self:InitTrainState(luxuryInfo, luxuryInfo.board.orderBoardId)
end
local bNormal = false
--for k,v in pairs(normalInfo.carbinInfo) do
-- if v.isOk then
-- bNormal = true
-- break;
-- end
--end
if normalInfo.carbinInfo ~= nil then
local normalEnmtor = normalInfo.carbinInfo:GetEnumerator();
while normalEnmtor:MoveNext() do
if  normalEnmtor.Current.isOk then
bNormal = true
break
end
end
end
local bLuxury = false
--for k,v in pairs(luxuryInfo.carbinInfo) do
-- if v.isOk then
-- bLuxury = true
-- break;
-- end
--end
if luxuryInfo.carbinInfo ~= nil then
local luxuryEnmtor = luxuryInfo.carbinInfo:GetEnumerator();
while luxuryEnmtor:MoveNext() do
local k2 = luxuryEnmtor.Current.Key
   local v2 = luxuryEnmtor.Current.Value
   print(k2)
   print(v2)


if  luxuryEnmtor.Current.isOk then
bLuxury = true
break
end
end
end
local bVis = normalInfo.isEmpty == false and bNormal or luxuryInfo.isEmpty == false and bLuxury
CS.Messenger.Broadcast(CS.TrainOrderEvent.TrainButtonRedHint, bVis);
else
self:handler(eventType, param)
end
end
)


xlua.hotfix(CS.TrainOrderHandler, 'FlushTrainNormalOrder', function (self)
if CS.FeatureProxy.Automatic:IsAvailable(CS.FeatureCategory.SYS_ID_17000014) == false then
return
end
print("-----lua -----TTTTTTTFlushTrainNormalOrder TYPE=" , CS.OrderBoardType.normal_train_board_id)
local minfo = CS.TrainOrderProxy.Automatic:GetTrainOrderInfoByBoardId(CS.OrderBoardType.normal_train_board_id)
--local Request = CS.Request()
        local temp1 = CS.Request(CS.APINameConst.FlushTrainOrder, CS.UserDataManager.Automatic.user.userId, minfo.board.slotIdss[0], CS.ServerTime.sInstance.ServerSecond)
local temp2 = temp1:SetImmediate(true)
local temp3 = temp2:Do(function(obj) self:FlushOrderSuccess(obj) end, function(obj, t) 
            CS.TrainOrderProxy.Instance.CanNormalFlush = true
        end)
end
)


xlua.hotfix(CS.TrainOrderHandler, 'FlushTrainLuxuryOrder', function (self)
if CS.FeatureProxy.Automatic:IsAvailable(CS.FeatureCategory.SYS_ID_17000015) == false then
return
end
print("-----lua -----TTTTTTTFlushTrainLuxuryOrder TYPE=", CS.OrderBoardType.luxury_train_board_id)
local minfo = CS.TrainOrderProxy.Automatic:GetTrainOrderInfoByBoardId(CS.OrderBoardType.luxury_train_board_id)
--local Request = CS.Request()
        local temp1 = CS.Request(CS.APINameConst.FlushTrainOrder, CS.UserDataManager.Automatic.user.userId, minfo.board.slotIdss[0], CS.ServerTime.sInstance.ServerSecond)
local temp2 = temp1:SetImmediate(true)
local temp3 = temp2:Do(function(obj) self:FlushOrderSuccess(obj) end, function(obj, t) 
            CS.TrainOrderProxy.Instance.CanLuxuryFlush = true
        end)
end
)


//////////////////////////////////////////////////////////////////



public staticclassHotfixCfg

{

[Hotfix]

    public static List<Type>subTypes

    {

        get

        {cfg.AddRange(GetTypesByBaseType(typeof(BaseCSEventHandler))); }

    }

static List<Type>GetTypesByBaseType(TypebaseType)

    {

        return (fromtypein Assembly.Load("Assembly-CSharp").GetTypes()

         where IsSubClassOf(type, baseType)

         select type).ToList();

    }

 

    static bool IsSubClassOf(Typetype,Type baseType)

    {

        var b = type.BaseType;

        while (b !=null)

        {

            if (b.Name ==baseType.Name)

            {

                return true;

            }

            b = b.BaseType;

        }

        return false;

    }

}

public classOrderHandler :BaseCSEventHandler {

public OrderHandler()

   {

       RegistEvent(System.Type.GetType("OrderEvent"));

       Messenger.AddListener(GameEnterEvent.LoginSuccess,handler);

       reward = new List<EntityData>();

       m_bCanTrackRewardRequest =true;

   }

   override protected void handler(string eventType,object[]param)

   {

       switch (eventType)

       {

            case OrderEvent.ClearReward:

                if (reward !=null)

                    reward.Clear();

                break;

            case OrderEvent.sOpenOrderPanel:

                ClickNormalOrderBoard(param);//打开普通订单面板

                break;

            case OrderEvent.ClickTrack:

                if (!DataManager.Instance.Available)return;

                if (BoardIds ==null)return;

                ClickTrack();

                break;

            case OrderEvent.sOrderDataParseEnd:

                OrderDataParseEnd(param);//订单解析服务器数据完成

                break;

            case OrderEvent.sTearOrder:

                TearOrder(param);//撕毁订单

                break;

            case OrderEvent.sFinishOrder:

                FinishOrder(param);//完成订单

                break;

            case OrderEvent.sSkipCoolDown:

                SkipOrderCooldown(param);//跳过订单冷却时间

                break;

            case OrderEvent.sOrderSelect:

                OrderSelect(param);//选择某个订单

                break;

            case GameEnterEvent.LoginSuccess:

                LoginSucess(param);

                break;

            case OrderEvent.InitGameHaveReward:

                m_bInitReward = true;

                Vo.OrderBoardRewardinitReward = (Vo.OrderBoardReward)param[0];

                m_initOrderBoardReward =initReward;

                List<EntityData>rewardlist =DataUtility.ConvertToEntityList(initReward.reward);

                reward.AddRange(rewardlist);

                OrderProxy.Instance.IsInitGameWaitClickReward =true;

                break;

       }

    }

private void FinishOrder(object[]param)

{/*//UIModule.Instance.CloseWindow(WindowName.sOrderPanel);

       if (CanHarvestReward)

       {

            HarvestOrderReward();

       }

       else

       {

            lastFinishedOrder =(NormalOrderInfo)param[0];

            torder = (NormalOrderInfo)param[0];

            List<int> needMaterial = newList<int>();

            if (torder.needMaterialEntitys !=null)

            {

                foreach (var cdata intorder.needMaterialEntitys)

                {

                   if (!cdata.bOk)

                    {

                       needMaterial.Add(cdata.itemDefId);

                       needMaterial.Add(cdata.count - cdata.currCount);

                    }

                }

            }

            if (needMaterial.Count > 0)

                newBuyMaterial().SetCallBacks(SuccesFinishOrder).SetCallBackParam(lastFinishedOrder,true).OpenBuyMaterialWindow(needMaterial, torder.orderConfig.orderId);

            else

            {

                SuccesFinishOrder(new object[]{ lastFinishedOrder, false });

            }

        }*/}

void SuccesFinishOrder(object[] param)

  {/*UIModule.Instance.CloseWindow(WindowName.sOrderPanel);

       //NormalOrderInfo torder = (NormalOrderInfo)param[0];

       bool bConsumeAnyWay = param.Length > 1 ? (bool)param[1] : false;

       if (torder == null) return;

 

       if (torder.needMaterialEntitys != null)

       {

            Vector3 scrPos =MapMath.Grid2ScreenPosition(TrackProxy.Instance.TrackInitGrid);//TouchWrapper.AveragePosition;

            var tmpParam = newEntityBehaviourParam()

            {

                hasAnim = true,

                animStartPos = scrPos,

            };

           EntityBehaviourManager.Instance.CheckAndDo(torder.needMaterialEntitys,tmpParam, () => { DeliverOrderImp(torder); }, bConsumeAnyWay);

       }

       else

           DeliverOrderImp(torder);*/}

 

//[LuaCallCSharp]

public classBuyMaterial

{

   //[CSharpCallLua]

   public delegate void VoidDelegate(object[] param);

 

   public List<List<int>>listNeedMaterial {get;private set; }

   public VoidDelegate successCallBack { get; private set; }

   public VoidDelegate failCallBack { get; private set; }

   public object[] callBackParam { get; private set; }

   public BuyMaterial()

   {

       listNeedMaterial = new List<List<int>>();

       successCallBack = null;

       failCallBack = null;

       callBackParam = null;

   }

 

   public BuyMaterial SetCallBacks(VoidDelegatesuccess=null,VoidDelegate fail=null)

   {

       successCallBack = success;

 

       //success(null);

 

       failCallBack = fail;

       return this;

   }

   public BuyMaterial SetCallBackParam(paramsobject[]param)

   {

       callBackParam = param;

       return this;

   }

   ///<summary>

   ///需要购买的物品列表,形式是[item1Id,item1Num,item2Id,item2Num,.....]

   ///</summary>

   ///<param name="param"></param>

   public void OpenBuyMaterialWindow(List<int>items,int exId = 0)

   {

       if (items ==null ||items.Count % 2 != 0)return;

       listNeedMaterial.Clear();

       for(inti=0,count=items.Count;i<count;i+=2)

       {

            List<int>tlist =new List<int>();

            tlist.Add((int)items[i]);

            tlist.Add((int)items[i + 1]);

            listNeedMaterial.Add(tlist);

       }

       Messenger.Broadcast(BuyMaterialEvent.OpenBuyMaterialPanel,newobject[] { this, exId });

   }

 

   ///<summary>

   ///需要分别购买的物品列表,形式是[item1Id,item1Num,item2Id,item2Num,.....]

   ///</summary>

   ///<param name="items"></param>

   ///<param name="showBtnConfirm"></param>

   ///<param name="exId"></param>

   ///<param name="okBtnTxt"></param>

   ///<param name="title"></param>

   public void OpenBuySplitMaterialWindow(List<int>items,bool showBtnConfirm =false, int exId = 0, stringokBtnTxt ="",string title = "")

   {

       if (items ==null ||items.Count % 2 != 0)

            return;

       listNeedMaterial.Clear();

       for (inti = 0,count = items.Count;i < count; i += 2)

       {

            List<int>tlist =new List<int>();

            tlist.Add((int)items[i]);

            tlist.Add((int)items[i + 1]);

            listNeedMaterial.Add(tlist);

       }

       Messenger.Broadcast(BuyMaterialEvent.OpenBuySplitMaterialUI,newobject[] { this, showBtnConfirm, exId, okBtnTxt, title });

   }

}

 

 

Debug.LogError("-----------CarOrder hot fix")

local util =require 'xlua.util'

 

xlua.private_accessible(CS.OrderHandler)

xutil.hotfix_ex(CS.OrderHandler,'handler', function (self,eventType,param)

       if(eventType ==CS.OrderEvent.sFinishOrder) then

              if (self.CanHarvestReward) then

                     Debug.LogError('harvest')

                     self:HarvestOrderReward()

        else

                     self.lastFinishedOrder =param[0]

                     self.torder =self.lastFinishedOrder

                     local needMaterial = {}

                     if self.torder andself.torder.needMaterialEntitys ~= nil then

                            local needMaterialEntitys= self.torder.needMaterialEntitys

                            local count =needMaterialEntitys.Count

                            for i =0,count-1 do

                                   local v =needMaterialEntitys[i]

                                   if (notv.bOk) then

                                          table.insert(needMaterial,v.itemDefId)

                                          table.insert(needMaterial,v.count - v.currCount)

                                   end

                            end

                     end

 

                     if #needMaterial > 0then

                            Debug.LogError('youwill buy')

                            self:FinishOrder(param)

                     else

                            Debug.LogError('donot need to buy')

                            local tem = {};

                            table.insert(tem,self.lastFinishedOrder)

                            table.insert(tem,false)

                            self:SuccesFinishOrder(tem)

                     end

        end

       else

              self:handler(eventType,param)

       end

end)

--[[xlua.private_accessible(CS.OrderHandler)

xlua.hotfix(CS.OrderHandler,'FinishOrder',

       function (self,param)

              if (self.CanHarvestReward) then

                     self:HarvestOrderReward()

              else

                     self.lastFinishedOrder =param[0]

                     self.torder =self.lastFinishedOrder

                     local needMaterial = {}

                     if self.torder and self.torder.needMaterialEntitys~= nil then

                            localneedMaterialEntitys = self.torder.needMaterialEntitys

                            local count =needMaterialEntitys.Count

                            for i =0,count-1 do

                                   local v =needMaterialEntitys[i]

                                   if (notv.bOk) then

                                          table.insert(needMaterial,v.itemDefId)

                                          table.insert(needMaterial,v.count - v.currCount)

                                   end

                            end

                     end

                     if #needMaterial > 0then

                            local buymaterial =      CS.BuyMaterial()

                            local temp1 =buymaterial:SetCallBacks(function(param1)

                                   self:SuccesFinishOrder(param1)

                            end,nil)

                            local temp2=temp1:SetCallBackParam(self.lastFinishedOrder,true)

                            temp2:OpenBuyMaterialWindow(needMaterial,self.torder.orderConfig.orderId)

                     else

                            local tem = {};

                            table.insert(tem,self.lastFinishedOrder)

                            table.insert(tem, false)

                            self:SuccesFinishOrder(tem)

                     end

              end

       end

)--]]

 

 

 

xlua.private_accessible(CS.OrderHandler)

xlua.hotfix(CS.OrderHandler,'FinishOrder',

       function (self,param)

              Debug.LogError("-----------CarOrder hot fix")

              if (self.CanHarvestReward) then

                     self:HarvestOrderReward()

              else

                     self.lastFinishedOrder =param[0]

                     self.torder =self.lastFinishedOrder

                     local needMaterial = {}

                     if self.torder andself.torder.needMaterialEntitys ~= nil then

                            localneedMaterialEntitys = self.torder.needMaterialEntitys

                            local count =needMaterialEntitys.Count

                            for i =0,count-1 do

                                   local v =needMaterialEntitys[i]

                                   if (notv.bOk) then

                                          table.insert(needMaterial,v.itemDefId)

                                          table.insert(needMaterial,v.count - v.currCount)

                                   end

                            end

                     end

                     if #needMaterial > 0then

                            local buymaterial =      CS.BuyMaterial()

                            --local d1 =CS.System.Delegate.CreateDelegate(CS.System.Type.GetType('BuyMaterial+VoidDelegate'),self, 'SuccesFinishOrder')

                            local d1 = util.createdelegate(CS.System.Type.GetType('BuyMaterial+VoidDelegate'), self, CS.OrderHandler, 'SuccesFinishOrder',{CS.System.Type.GetType('System.Object[]')})

                            local temp1 =buymaterial:SetCallBacks(d1,nil)

                            local temp2=temp1:SetCallBackParam(self.lastFinishedOrder,true)

                            temp2:OpenBuyMaterialWindow(needMaterial,self.torder.orderConfig.orderId)

                     else

                            local tem = {};

                            table.insert(tem,self.lastFinishedOrder)

                            table.insert(tem,false)

                            self:SuccesFinishOrder(tem)

                     end

              end

       end

)

 

 

xlua.hotfix(CS.OrderHandler,'SuccesFinishOrder',

       function(self, param)                

              CS.JunEngine.UI.UIModule.Instance:CloseWindow(CS.WindowName.sOrderPanel)

        if (self.torder == nil) then

                     return

              end

        if (self.torder.needMaterialEntitys ~=nil) then

            local scrPos =CS.MapMath.Grid2ScreenPosition(CS.TrackProxy.Instance.TrackInitGrid)

            local tmpParam =CS.EntityBehaviourParam()

                     tmpParam.hasAnim = true

                     tmpParam.animStartPos =scrPos

                     local bConsumeAnyWay =false

                     if param.Length > 1 then

                            bConsumeAnyWay =param[1]

                     else

                            bConsumeAnyWay =false

                     end              

           CS.EntityBehaviourManager.Instance:CheckAndDo(self.torder.needMaterialEntitys,tmpParam, function()

                            print('callmyDeliver')

                            self:DeliverOrderImp(self.torder)

                     end, bConsumeAnyWay)

        else

            self:DeliverOrderImp(self.torder)

              end

       end

)

 

 

 

C#hotfix热修复

xlua.private_accessible(CS.OrderHandler)

xlua.hotfix(CS.OrderHandler,'FinishOrder',

       function (self,param)

              if (self.CanHarvestReward) then

                     self:HarvestOrderReward()

              else

                     self.lastFinishedOrder =param[0]

                     self.torder =self.lastFinishedOrder

                     local needMaterial = {}

                     if self.torder andself.torder.needMaterialEntitys ~= nil then

                            localneedMaterialEntitys = self.torder.needMaterialEntitys

                            local count =needMaterialEntitys.Count

                            for i =0,count-1 do

                                   local v =needMaterialEntitys[i]

                                   if (notv.bOk) then

                                          table.insert(needMaterial,v.itemDefId)

                                          table.insert(needMaterial,v.count - v.currCount)

                                   end

                            end

                     end

                     if #needMaterial > 0then

                            local buymaterial =      CS.BuyMaterial()

                            local temp1 =buymaterial:SetCallBacks(function(param1)

                                   self:SuccesFinishOrder(param1)

                            end,nil)

                            local temp2=temp1:SetCallBackParam(self.lastFinishedOrder,true)

                            temp2:OpenBuyMaterialWindow(needMaterial,self.torder.orderConfig.orderId)

                     else

                            local tem = {};

                            table.insert(tem,self.lastFinishedOrder)

                            table.insert(tem,false)

                            self:SuccesFinishOrder(tem)

                     end

              end

       end

)

 

 

 

 

xlua的util.createdelegate应用

原创 2017年08月17日 14:44:34

·        标签:

·        xlua /

·        util.createdelegate /

·        unity3d /

·        泛型 /

·        委托

·        52

local util = require 'xlua.util'
local obj = CS.TestClass()
local d1 = util.createdelegate(CS.System.Type.GetType('TestClass+TestDelegate'),obj, CS.TestClass, 'Foo', {typeof(CS.System.Int32)}) 

print(d1)
local type2 = CS.System.Type.GetType('TabButtonInfo+CanClick')
local d2 = util.createdelegate(type2, obj, CS.TestClass, 'CanClick', {}) 
print(d2)
local type3 = CS.System.Type.GetType('NoticeTweenPosition+EventTrigger')
local d3 = util.createdelegate(type3, obj, CS.TestClass, 'Trigger', {}) 
print(d3)
local type4 = CS.System.Type.GetType('NoticeTweenPosition+Finished')
local d4 = util.createdelegate(type4, obj, CS.TestClass, 'Trigger', {}) 
print(d4)
local type5 = CS.System.Type.GetType('BaseItemContext+OnPress')
local d5 = util.createdelegate(type5, obj, CS.TestClass, 'OnPress',{typeof(CS.BaseItemContext)}) 
print(d5)
local type6 = CS.System.Type.GetType('PageGodPvp+Action')
local d6 = util.createdelegate(type6, obj, CS.TestClass, 'Action',{typeof(CS.System.Single)}) 
print(d6)
local type7 = CS.System.Type.GetType('UICustomCheckbox+OnStateChange')
local d7 = util.createdelegate(type7, obj, CS.TestClass, 'OnStateChange',{typeof(CS.System.Boolean)}) 
print(d7)
local type8 = CS.System.Type.GetType('Tools+Action')
local d8 = util.createdelegate(type8, obj, CS.TestClass, 'Action',{typeof(CS.System.Single)}) 
print(d8)
local type9 = CS.System.Type.GetType('System.Action`1[System.Int32]')
local d9 = util.createdelegate(type9, obj, CS.TestClass, 'Foo',{typeof(CS.System.Int32)}) 
print(d9)
local type10 = CS.System['Action`2[System.Int32,System.Int32]']
local d10 = util.createdelegate(type10, obj, CS.TestClass, 'ActionIntInt',{typeof(CS.System.Int32),typeof(CS.System.Int32)}) 
print(d10)
local type11 =CS.System.Type.GetType('System.Action`2[[AI,Assembly-CSharp],[AI,Assembly-CSharp]],System.Core')
local d11 = util.createdelegate(type11, obj, CS.TestClass, 'ActionAiAi',{typeof(CS.AI),typeof(CS.AI)}) 
print(d11)
local type12 = CS.System.Type.GetType('System.Action`2[[System.String,mscorlib],[UnityEngine.Vector3, UnityEngine]],System.Core')

local dic = CS.System.Activator.CreateInstance(CS.System.Type.GetType('System.Collections.Generic.Dictionary`2[[System.String,mscorlib],[UnityEngine.Vector3, UnityEngine]],mscorlib'))
dic:Add('a', CS.UnityEngine.Vector3(1, 2, 3))
print(dic:TryGetValue('a'))


--C#
--public class TestClass
--{
-- public void Foo(int a){}
-- public delegate void TestDelegate(int a);
-- public string CanClick(){return string.Empty;}
-- public void Trigger(){ }
-- public void OnPress(BaseItemContext item){}
-- public void Action(float time){}
-- public void OnStateChange(bool flag){}
-- public void ActionIntInt(int a,int b){ }
-- public void ActionIntInt(AI a,AI b){ }
--}

怎么把C#的函数赋值给一个委托字段

2.1.8及之前版本,你把C#函数当成一个lua函数即可,性能会略低,因为委托调用时先通过Birdage适配代码调用lua,然后lua再调用回C#

2.1.9xlua.util新增createdelegate函数

比如如下C#代码

publicclassTestClass
{
    publicvoidFoo(int a)
    { 
    }
         
    publicstaticvoidSFoo(int a)
    {
    }
publicdelegate void TestDelegate(int a);

你可以指明用Foo函数创建一个TestDelegate实例

local util =require'xlua.util'
 
local d1 = util.createdelegate(CS.TestDelegate, obj, CS.TestClass, 'Foo', {typeof(CS.System.Int32)}) --由于Foo是实例方法,所以参数2需要传TestClass实例
local d2 = util.createdelegate(CS.TestDelegate, nil, CS.TestClass, 'SFoo', {typeof(CS.System.Int32)})
 
obj_has_TestDelegate.field = d1 + d2 --到时调用field的时候将会触发FooSFoo,这不会经过Lua适配
原创粉丝点击