I am a beginning coder trying to make a math app for kids. I have been trying to incorporate calculator type user input into the game but am going nowhere fast. I dont want the app to be simply multiple choice. E.G., I have 3D numbers as buttons (that do various tricks) but they need to input real usable data into a text field (?) I’ve made the selectable Number GO’s, as GUI buttons, but I don’t know how to assign them sequentially as an answer to simple equations: a + b = ? etc. I presume I’ll need an enter button like a calculator…
Can anyone just point me in a workable direction? Many thanks in advance for any advice. Perhaps, a tut I might look at?
I must say, that I am amazed at the generosity of Unity Community and am thrilled to be a part of it.
using UnityEngine;
using System.Collections;
public class Calc : MonoBehaviour {
string val;
int temp;
Rect text,button1, button2,button3,buttonPlus,buttonEqual;
bool endOfCalc;
void Start () {
text = new Rect (10, 10, 200, 20);
button1 = new Rect (10, 30, 20, 20);
button2 = new Rect (30, 30, 20, 20);
button3 = new Rect(50,30,20,20);
buttonPlus = new Rect (70, 30, 20, 20);
buttonEqual = new Rect (90, 30, 20, 20);
val ="";
endOfCalc = false;
}
// Update is called once per frame
void OnGUI () {
GUI.TextField (text, val);
if(GUI.Button (button1,"1")){
Calculation("1");
}
if(GUI.Button (button2,"2")){
Calculation("2");
}
if(GUI.Button (button3,"3")){
Calculation("3");
}
if(GUI.Button (buttonPlus,"+")){
temp +=int.Parse(val);
val = "";
}
if(GUI.Button (buttonEqual,"=")){
temp +=int.Parse(val);
val = temp.ToString();
endOfCalc = true;
}
}
void Calculation(string str){
if(!endOfCalc)
val += str;
else{
val = "";
val += str;
endOfCalc = false;
temp = 0;
}
}
}
It only has three values and one operation but the principle remains the same for other operation. You can also change the layout ans some actions at will.
The Calculation method simply check if we are done with the calculation, that is to erase the previous one.
The logic is largely not Unity. If you Google combinations of ‘calculator’ ‘simple’ ‘source’ ‘app’ ‘stack’ ‘C#’, you will find numerous hits and bodies of code. Writing a simple calculator app can be found in entry-level computer science courses, often in conjunction with the introduction of the ‘Stack’ data structure. It is a good data structure for accumulating and processing the input from your buttons, and there is a class for it available inside Unity.
One method of implementing the calculator would be to have a central class that collects input and process data. As a first step, you might want to figure out how to communicate between your buttons and a single, bare-bones class that simply outputs a unique message for each button pressed.
Amazing! Thanks for everyone’s generosity. Haven’t had a moment to really scrutinize it— day job and friends visiting. I’ll get back. Hopefully I can do something clever with it.