统一3d OnGUI循环

时间:2013-06-10 10:56:12

标签: c# unity3d

我有一个小问题我正在制作计算器,我想通过写入循环减少我的代码长度,对于数字部分,我解决了无限循环(“OnGUI”)部分的问题,但现在它不会显示我的任何数字,有人可以向我解释为什么会这样吗? 谢谢。

using UnityEngine;
using System.Collections;

public class Calculator : MonoBehaviour {
    int temp,rectX,t,count;
    bool endOfCalc;
    string val;

    private void Start()
    {
        endOfCalc = false;
        val = "";
        temp = 0;
        t = 9;
        count = 0;

        /*for(int x = 0; x <= 9; x++)
        {
            rectX += 20;
            Debug.Log (rectX);
            if (GUI.Button (new Rect(10,160+rectX,30,20), x.ToString ()))
            {
                Calculation(x.ToString ());
            }
        }*/

    }

    private void OnGUI()
    {
        val = GUI.TextField (new Rect(10,100,200,20), val);

        if (GUI.Button (new Rect(40,120,30,20), "+"))
        {
            temp += int.Parse (val);
            val = "";
        }

        if (GUI.Button (new Rect(10,120,30,20),"="))
        {
            temp += int.Parse (val);
            val = temp.ToString ();
            endOfCalc = true;
        }

        // The problem is here, i can't see any buttons.
        for(int x= 0; x<=t; t--)
        {
            if (GUI.Button (new Rect(10,140,30,20), count.ToString()))
            {
                Calculation(count.ToString ());
            }

            count++;
        }
    }

    void Calculation(string str)
    {
        if (!endOfCalc)
            val += str;
        else
            val = "";
            val += str;
            endOfCalc = false;
            temp = 0;
    }
}

3 个答案:

答案 0 :(得分:1)

for(int x= 0; x<=t; t--)

我认为这一定是:

for(int x= 0; x<=t; x++)
每帧至少调用一次

OnGui。在当前实现中,t在第一次调用期间递减为-1,并且将保持为-1,因为我看不到将其设置回9的任何其他位置。

另一点是Rect:所有按钮都显示在同一位置。 rectX中注释的Start偏移方法似乎是您所需要的。但是由于Rect的构造函数,rectX实际上是一个rectY。

我认为你避免使用count因为它似乎没有被初始化:

for(int x= 0; x<=t; x++) { 
    if (GUI.Button (new Rect(10,140,30,20), x.ToString())) {
        Calculation(x.ToString ());
    }
}

<强> [更新]

我刚刚尝试了以下代码:

void OnGUI () {
    int offset = 0;
    for (int x = 0; x <= 9; x++) { 
        if (GUI.Button (new Rect (10 + offset, 140, 30, 20), x.ToString ())) {
            Debug.Log ("Pressed: " + x);
        }
        offset += 35;
    }       
}

得到了:
Buttons created by for loop

和一些日志输出如下:

Pressed: 4
UnityEngine.Debug:Log(Object)
MenuController:OnGUI() (at Assets/Scripts/Menu/MenuController.cs:53)

答案 1 :(得分:0)

当我查看你的代码时,我会说你只看到一个按钮,而其他所有按钮都在那个按钮之下,因为你总是将它们放在完全相同的位置:

if (GUI.Button (new Rect(10,140,30,20), count.ToString()))
{
    Calculation(count.ToString ());
}

你必须改变每一轮的位置,如下所示:

if (GUI.Button (new Rect(10,30 * t + 140,30,20), count.ToString()))
{
    Calculation(count.ToString ());
}

答案 2 :(得分:0)

看起来这有点复杂,在OnGUI类中如果写for (int x = 0; x<= 9; x++)我们会遇到麻烦,因为在OnGUI中这个类每次被调用两次所以每帧两次x将是== 0并且将从0循环到9这就是一个问题,因为我只需要循环一次,因为我可以使用启动功能,但我不知道如何调用GUI.Button...以便这是另一个问题所以我骗了系统并使用从9到0计数和固定的无限循环,但问题不存在当我修复无限循环我写在那个循环中的例子:GUI.button它不会出现,我需要解释为什么就是这样,感谢阅读。 :)感谢您的回答。