通过对井字棋代码的学习,了解 OnGUI() 事件,提升阅读 API 文档能力,在编写代码时能运用数据-控制分离的编程思维,现在尝试参考“井字棋”案例,制作一个简单的计算器。
成果演示:
unity3d计算器效果展示-其他-高清完整正版视频在线观看-优酷 (youku.com)
首先创建一个3D工程项目,再在Assets中创建一个脚本,命名为cal
然后打开cal.cs,编写脚本。由于只需要用到IMGUI及OnGui()函数绘制UI界面,不需要建立其他模型。代码需要实现的内容有:最基本的加减乘除运算。
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class 计算器 : MonoBehaviour
{
// 模型
public class CalculatorModel
{
public string Operand1 { get; set; } = "";
public string Operand2 { get; set; } = "";
public float Result { get; set; }
public string Operator { get; set; }
public string Process { get; set; } = "";
public bool IsEnteringSecondOperand { get; set; } = false;
}
// 控制器
public class CalculatorController
{
private CalculatorModel _model;
public CalculatorController(CalculatorModel model)
{
_model = model;
}
public void Calculate()
{
float operand1 = float.Parse(_model.Operand1);
float operand2 = float.Parse(_model.Operand2);
switch (_model.Operator)
{
case "+":
_model.Result = operand1 + operand2;
break;
case "-":
_model.Result = operand1 - operand2;
break;
case "*":
_model.Result = operand1 * operand2;
break;
case "/":
_model.Result = operand1 / operand2;
break;
}
_model.Process += _model.Operand1 + " " + _model.Operator + " " + _model.Operand2 + " = " + _model.Result + "\n";
_model.Operand1 = "";
_model.Operand2 = "";
_model.IsEnteringSecondOperand = false;
}
public void OnGUI()
{
for (int i = 0; i <= 9; i++)
{
if (GUI.Button(new Rect(10 + (i % 3) * 70, 10 + (i / 3) * 30, 60, 20), i.ToString()))
{
if (_model.IsEnteringSecondOperand)
{
_model.Operand2 += i.ToString();
}
else
{
_model.Operand1 += i.ToString();
}
}
}
if (GUI.Button(new Rect(10, 130, 60, 20), "+"))
{
_model.Operator = "+";
_model.IsEnteringSecondOperand = true;
}
if (GUI.Button(new Rect(80, 130, 60, 20), "-"))
{
_model.Operator = "-";
_model.IsEnteringSecondOperand = true;
}
if (GUI.Button(new Rect(150, 130, 60, 20), "*"))
{
_model.Operator = "*";
_model.IsEnteringSecondOperand = true;
}
if (GUI.Button(new Rect(220, 130, 60, 20), "/"))
{
_model.Operator = "/";
_model.IsEnteringSecondOperand = true;
}
if (GUI.Button(new Rect(10, 160, 200, 20), "Calculate"))
{
Calculate();
}
GUI.Label(new Rect(10, 190, 200, 20), "Result: " + _model.Result);
GUI.TextArea(new Rect(10, 220, 280, 100), _model.Process);
// 显示当前输入
string currentInput = _model.IsEnteringSecondOperand ? _model.Operand2 : _model.Operand1;
GUI.TextField(new Rect(10, 330, 200, 20), currentInput);
}
}
//系统指在游戏循环驱动下,运用部件完成游戏逻辑。
private CalculatorModel _model;
private CalculatorController _controller;
// Start is called before the first frame update
void Start()
{
_model = new CalculatorModel();
_controller = new CalculatorController(_model);
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
_controller.OnGUI();
}
}
编写完脚本代码后,创建一个空的模型(Create Empty),命名为int,将calculator.cs拖动到init上面
点击play运行,检验功能完成度。
小结:计算器逻辑简单,适合进行初步上手,用于熟悉C#的编码,锻炼数据-控制分离的编程思维。