在行为树中,需要扩展的主要是行为节点和条件节点。一般来说,每当要创建一个节点时,就要新建一个节点文件。而对于一些简单的行为节点和条件节点,为了去掉新建文件的过程,可以写一个通用版本的行为节点和条件节点,以传入方法的方式来避免新建文件。
BTActionUniversal.lua
1 --[[ 2 通用Action节点 3 --]] 4 BTActionUniversal = BTAction:New(); 5 6 local this = BTActionUniversal; 7 this.name = "BTActionUniversal"; 8 9 function this:New(enterFunc, executeFunc, exitFunc) 10 local o = {}; 11 setmetatable(o, self); 12 self.__index = self; 13 o.enterFunc = enterFunc; 14 o.executeFunc = executeFunc; 15 o.exitFunc = exitFunc; 16 return o; 17 end 18 19 function this:Enter() 20 if (self.enterFunc) then 21 self.enterFunc(); 22 end 23 end 24 25 function this:Execute() 26 if (self.executeFunc) then 27 return self.executeFunc(); 28 else 29 return BTTaskStatus.Failure; 30 end 31 end 32 33 function this:Exit() 34 if (self.exitFunc) then 35 self.exitFunc(); 36 end 37 end
BTConditionalUniversal.lua
1 --[[ 2 通用Conditional节点 3 --]] 4 BTConditionalUniversal = BTConditional:New(); 5 6 local this = BTConditionalUniversal; 7 this.name = "BTConditionalUniversal"; 8 9 function this:New(checkFunc) 10 local o = {}; 11 setmetatable(o, self); 12 self.__index = self; 13 o.checkFunc = checkFunc; 14 return o; 15 end 16 17 function this:Check() 18 return self.checkFunc(); 19 end
TestBehaviorTree.lua
1 TestBehaviorTree = BTBehaviorTree:New(); 2 3 local this = TestBehaviorTree; 4 this.name = "TestBehaviorTree"; 5 6 function this:New() 7 local o = {}; 8 setmetatable(o, self); 9 self.__index = self; 10 o:Init(); 11 return o; 12 end 13 14 function this:Init() 15 local sequence = BTSequence:New(); 16 local conditional = self:GetBTConditionalUniversal(); 17 local action = self:GetBTActionUniversal(); 18 local log = BTLog:New("This is log!!!"); 19 log.name = "log"; 20 21 self:SetStartTask(sequence); 22 23 sequence:AddChild(conditional); 24 sequence:AddChild(action); 25 sequence:AddChild(log); 26 end 27 28 function this:GetBTConditionalUniversal() 29 local a = function () 30 return (2 > 1); 31 end 32 local universal = BTConditionalUniversal:New(a); 33 return universal; 34 end 35 36 function this:GetBTActionUniversal() 37 local count = 1; 38 local a = function () print("11"); end 39 local b = function () 40 if (count < 3) then 41 count = count + 1; 42 print("22"); 43 return BTTaskStatus.Running; 44 else 45 return BTTaskStatus.Success; 46 end 47 end 48 local c = function () print("33"); end 49 local universal = BTActionUniversal:New(a, b, c); 50 return universal; 51 end
打印如下:
分类:
Unity插件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?