Unity使用多态制作计算器功能
程序员文章站
2022-01-03 19:06:18
本文实例为大家分享了unity使用多态制作计算器,供大家参考,具体内容如下unity中需要的组件在unity中创建两个inputfield,一个dropdown,一个button和一个text创建脚本...
本文实例为大家分享了unity使用多态制作计算器,供大家参考,具体内容如下
unity中需要的组件
在unity中创建两个inputfield,一个dropdown,一个button和一个text
创建脚本文件
计算父类
using system.collections; using system.collections.generic; using unityengine; public class jsq : monobehaviour { public abstract class calculate { public float number1 { get; set; } public float number2 { get; set; } public abstract float compute(); } }
加法
using system.collections; using system.collections.generic; using unityengine; public class addition : jsq.calculate { /// <summary> /// 实现父类计算方法 /// </summary> /// <returns>加法计算结果</returns> public override float compute() { return number1 + number2; } }
减法
using system.collections; using system.collections.generic; using unityengine; public class subtraction : jsq.calculate { /// <summary> /// 实现父类计算方法 /// </summary> /// <returns>减法计算结果</returns> public override float compute() { return number1 - number2; } }
乘法
using system.collections; using system.collections.generic; using unityengine; public class multiplication : jsq.calculate { public override float compute() { return number1 * number2; } }
除法
using system.collections; using system.collections.generic; using unityengine; public class newbehaviourscript : jsq.calculate { public override float compute() { return number1 / number2; } }
等于号按钮
using system.collections; using system.collections.generic; using unityengine; using unityengine.ui; using system; public class equalbtn : jsq { public text txt_number1; public text txt_number2; public text cbb_operator; public text lab_result; public void btn_click() { //获取两个参数 float number1 = convert.tosingle(txt_number1.text.trim()); float number2 = convert.tosingle(txt_number2.text.trim()); //获取运算符 string operation = cbb_operator.text.trim(); //通过运算符,返回父类类型 calculate calculate = getcalculateresult(operation); calculate.number1 = number1; calculate.number2 = number2; //利用多态返回运算结果 string result = calculate.compute().tostring(); this.lab_result.text = result; } private calculate getcalculateresult(string operation) { calculate calculate = null; switch (operation) { case "+": calculate = new addition(); break; case "-": calculate = new subtraction(); break; case "*": calculate = new multiplication(); break; case "/": calculate = new division(); break; } return calculate; } }
将等于号按钮脚本赋给canvas组件
再将对应的组件拉进去:顺序分别是第一个inputfield里的text(注意都是text),第二个inputfield里的text,然后是dropdown里面的label,最后是显示结果的text
最后在给等于号按钮添加一个执行函数
最后在运行unity,加减乘除都可以计算,大功告成!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Unity Shader实现模糊效果