本篇内容介绍了“Unity使用多态制作计算器功能代码分享”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
本文实例为大家分享了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使用多态制作计算器功能代码分享”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!