网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 知识问答

Unity 设计模式之 模板方法模式的实例介绍

时间:2024-10-12 03:05:44

1、打开Unity,新建一个空工程,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

2、在工程中,新建几个脚本,然后双击打开,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

3、脚本的具体代码和代码说明如下图

Unity 设计模式之 模板方法模式的实例介绍Unity 设计模式之 模板方法模式的实例介绍Unity 设计模式之 模板方法模式的实例介绍Unity 设计模式之 模板方法模式的实例介绍

4、TestPaperTemplateClass 脚本具体内容如下:usingUnityEngine;publicclassTestPaperTemplateClass{publicvoidTestQuestion1(){ Debug.Log("1+2=[]a.2b.1c.3"); Debug.Log("答案:"+Answer1()); }publicvirtualstringAnswer1(){ return""; }publicvoidTestQuestion2(){ Debug.Log("1*2=[]a.2b.1c.3"); Debug.Log("答案:"+Answer2()); } publicvirtualstringAnswer2(){ return""; }}

5、TestPaperAConcreteClass脚本具体内容如下:publicclassTestPaperAConcreteClass:TestPaperTemplateClass{publicoverridestringAnswer1() { return"a"; }publicoverridestringAnswer2() { return"b"; }}

6、TestPaperBConcreteClass脚本具体内容如下:publicclassTestPaperBConcreteClass:TestPaperTemplateClass{publicoverridestringAnswer1() { return"c"; }publicoverridestringAnswer2() { return"a"; }}

7、Test脚本具体内容如下:usingUnityEngine;publicclassTest:MonoBehaviour{//Usethisforinitialization voidStart(){Debug.Log("TestPaperA:"); TestPaperAConcreteClasstestPaperA=newTestPaperAConcreteClass(); testPaperA.TestQuestion1(); testPaperA.TestQuestion2();Debug.Log("TestPaperB:"); TestPaperBConcreteClasstestPaperB=newTestPaperBConcreteClass(); testPaperB.TestQuestion1(); testPaperB.TestQuestion2();}}

8、脚本编译正确,回到Unity界面,在场景中新建一个 GameObject,并把 Test 脚本赋给 GameObject,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

9、运行场景,控制台 Console 打印如下图

Unity 设计模式之 模板方法模式的实例介绍

10、到此,《Unity 设计模式之 模板方法模式的实例介绍》讲解结束,谢谢

© 2026 一点资料
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com