Unity Referencing输入字段文本框

时间:2017-03-19 02:13:42

标签: c# sqlite unity3d

在这里完成noob:我想要做的是一个简单的注册屏幕,其中文本输入字段可以保存到SQLite数据库中。正如你所看到的那样,大多数都是预定义的字符串,因为我还在测试它。我有一个应插入值的脚本,它附加到一个按钮,并在单击后调用InsertScore函数。插入函数有效,它只是我需要将文本从输入字段存储到变量现在或直接在此处引用它:cmd.Parameters.Add(new SqliteParameter("@EmployeeID",

无论如何,为什么我不能在C#中引用txtEmployeeID(我的输入字段的名称)?或者更好,请告诉我如何引用txtEmployeeID输入字段。这样我就可以获取其中的字符串或文本并将其保存到数据库中。

public void InsertScore()
{

connectionString = "URI=file:" + Application.dataPath + "/HighScoreDB.sqlite";

using (SqliteConnection con = new SqliteConnection(connectionString))
{



SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = @"INSERT INTO HighScores(EmployeeID, EmployeeFirstname, TestScore, ROLE) VALUES (@EmployeeID,@EmployeeFirstName,@TestScore,@Role)";
cmd.Connection = con;
//cmd.Parameters.Add(new SqliteParameter("@EmployeeID", "222222"));
//cmd.Parameters.Add(new SqliteParameter("@EmployeeID", gameObject.GetComponent<input>
cmd.Parameters.Add(new SqliteParameter("@EmployeeFirstName", "Anand3"));
cmd.Parameters.Add(new SqliteParameter("@TestScore", "65"));
cmd.Parameters.Add(new SqliteParameter("@Role", "Tester"));

con.Open();

cmd.ExecuteNonQuery();

}

}


​

1 个答案:

答案 0 :(得分:1)

  

如何引用txtEmployeeID输入字段

使用GameObject.Find("txtEmployeeID")查找输入GameObject,然后对返回的GameObject执行GetComponent以获取InputField组件。

private InputField employerIdinputField;

void Start()
{
    employerIdinputField = GameObject.Find("txtEmployeeID").GetComponent<InputField>();

    string dataFromInput = employerIdinputField.text;
}

将其纳入您当前的代码:

private InputField employerIdinputField;

void Start()
{
    employerIdinputField = GameObject.Find("txtEmployeeID").GetComponent<InputField>();
}

public void InsertScore()
{

   connectionString = "URI=file:" + Application.dataPath + "/HighScoreDB.sqlite";

    using (SqliteConnection con = new SqliteConnection(connectionString))
    {

    SqliteCommand cmd = new SqliteCommand();
    cmd.CommandText = @"INSERT INTO HighScores(EmployeeID, EmployeeFirstname,    TestScore, ROLE) VALUES (@EmployeeID,@EmployeeFirstName,@TestScore,@Role)";
    cmd.Connection = con;

    //FIXED LINE!
    cmd.Parameters.Add(new  SqliteParameter("@EmployeeID",employerIdinputField.text));
    cmd.Parameters.Add(new SqliteParameter("@EmployeeFirstName", "Anand3"));
    cmd.Parameters.Add(new SqliteParameter("@TestScore", "65"));
    cmd.Parameters.Add(new SqliteParameter("@Role", "Tester"));
    con.Open();
    cmd.ExecuteNonQuery();
    }
}

对于InputField事件,请检查 3 .InputField Component here