OnGUI: Called multiple times per frame in response to GUI events. The Layout and Repaint events are processed first, followed by a Layout and keyboard/mouse event for each input event. 这个函数其实就是用来渲染GUI以及相应处理GUI事件的函数。每一帧可能被调起很多次来处理这些事件。
下面是具体代码。
using UnityEngine; using System.Collections; public class GUIcreater : MonoBehaviour { public GUIStyle buttonstyle; string text=""; public class mycocluator{ float[] operation_number = new float[100]; int on_top = -1; char[] operation = new char[100]; int o_top = -1; public string computer(string s) { int i = 0; while (i < s.Length) { switch (s [i]) { case '+': operation [o_top + 1] = '+'; o_top++; break; case '-': operation [o_top + 1] = '-'; o_top++; break; case '*': operation [o_top + 1] = '*'; o_top++; break; case '/': operation [o_top + 1] = '/'; o_top++; break; } int j = 0; string temps = ""; while (((i+j) < s.Length) && (s [i + j] == '.' || (s [i + j] <= '9' && s [i + j] >= '0'))) { temps += s [i + j]; j++; } if (j != 0) { float temp = float.Parse (temps); on_top++; operation_number [on_top] = temp; i += j; } else { i++; } } int k = 0; while (o_top > -1) { Debug.Log (k); k++; float temp1, temp2; char tempc; Debug.Log ("o_top:" + o_top); if (o_top == -1) break; tempc = operation [o_top]; o_top--; Debug.Log ("o_top:" + o_top); temp1 = operation_number [on_top]; on_top--; temp2 = operation_number [on_top]; on_top--; switch (tempc) { case '+': operation_number [on_top + 1] = temp1 + temp2; on_top++; break; case '-': operation_number [on_top + 1] = temp2 - temp1; on_top++; break; case '*': operation_number [on_top + 1] = temp1 * temp2; on_top++; break; case '/': operation_number [on_top + 1] = temp2 / temp1; on_top++; break; } } Debug.Log (operation_number [on_top].ToString ()); return operation_number [on_top].ToString(); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI(){ GUI.Box(new Rect (10, 10, 290, 50), text); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (GUI.Button (new Rect (10 + i * 60, 100 + j * 60, 50, 50), 1 + j * 3 + i + "", "button")) { text += 1 + j * 3 + i; } } } if (GUI.Button (new Rect (190, 100 , 50, 50), "C", "button")) { text =""; } if (GUI.Button (new Rect (250, 100 , 50, 50), "<-", "button")) { if (text.Length > 0) text = text.Remove(text.Length-1,1) ; } if (GUI.Button (new Rect (10, 280 , 110, 50), "0", "button")) { text +="0"; } if (GUI.Button (new Rect (130, 280 , 50, 50), ".", "button")) { text +="."; } if (GUI.Button (new Rect (190, 160 , 50, 50), "+", "button")) { text +="+"; } if (GUI.Button (new Rect (190, 220 , 50, 50), "-", "button")) { text +="-"; } if (GUI.Button (new Rect (250, 160 , 50, 50), "x", "button")) { text +="*"; } if (GUI.Button (new Rect (250, 220 , 50, 50), "/", "button")) { text +="/"; } if (GUI.Button (new Rect (190, 280 , 110, 50), "=", "button")) { mycocluator c = new mycocluator (); text = c.computer(text); } } }