使用C#编写Unity GUI的文本框

4

我正在Unity中制作一个注册场景,使用了以下脚本来添加文本框和按钮,但是当我播放时无法在文本框中输入文字。我的代码有什么问题?

void OnGUI () {

    string email = "";
    string username = "";
    string password = "";
    string confirm = "";

    email = GUI.TextField (new Rect (250, 93, 250, 25), email, 40);
    username = GUI.TextField ( new Rect (250, 125, 250, 25), username, 40);
    password = GUI.PasswordField (new Rect (250, 157, 250, 25), password, "*"[0], 40);
    confirm = GUI.PasswordField (new Rect (300, 189, 200, 25), confirm, "*"[0], 40);

    if (GUI.Button (new Rect (300, 250, 100, 30), "Sign-up")) {
        Debug.Log(email + " " + username + " " + password + " " + confirm);
    }
}
1个回答

3
将输入变量作为您的类/脚本的成员而不是方法进行存储。每个帧都将其重置为空字符串,擦除用户尝试输入的内容。
来自Unity3D文档关于text参数的注意事项:

要编辑的文本。应将此函数的返回值分配回字符串,如示例所示。

尝试更改您的代码为:
//notice these are pulled out from the method and now attached to the script
string email = ""; 
string username = "";
string password = "";
string confirm = "";

void OnGUI () {

    email = GUI.TextField (new Rect (250, 93, 250, 25), email, 40);
    username = GUI.TextField ( new Rect (250, 125, 250, 25), username, 40);
    password = GUI.PasswordField (new Rect (250, 157, 250, 25), password, "*"[0], 40);
    confirm = GUI.PasswordField (new Rect (300, 189, 200, 25), confirm, "*"[0], 40);

    if (GUI.Button (new Rect (300, 250, 100, 30), "Sign-up")) {
        Debug.Log(email + " " + username + " " + password + " " + confirm);
    }
}

@DannikaRodriguez 如果这个回答对您的问题有帮助,请选择旁边的“打勾”以表示它是正确的答案。 - Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接