unity3d游戏开发之成功实现对数据库读取登陆


1,创建一个数据库表,我们就以 test数据库为例,数据库里建一个tb_User表, tb_User里有User_Name , User_Pass 字段.

2,创建一个验证用户基本信息的asp.net页面,页面名字是:Default.aspx

后台代码如下:
  1. using System;
  2. using System.Configuration;
  3. using System.Data;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.HtmlControls;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Data.SqlClient;

  11. public partial class _Default : System.Web.UI.Page
  12. {

  13. SqlConnection conn = new SqlConnection("Data Source=.sqlexpress2008;Initial Catalog=test;Integrated Security=True");

  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. string name = Request.Form["name2";
  17. string pwd=Request.Form["pwd";

  18. conn.Open();

  19. string sql = "select User_Name from tb_User where User_Name='" + name + "' and User_Pass='"+pwd+"'";
  20. SqlCommand cmd = new SqlCommand(sql, conn);
  21. if (cmd.ExecuteScalar() != null)
  22. Response.Write("success");
  23. else
  24. Response.Write("faield");
  25. conn.Close();
  26. }
  27. }
复制代码



前台代码不用管.

3,新建一个Unity 3D项目,新建一个Javascript文件, 在Javascript文件上编写如下代码:

  1. var URL = "http://devmac.net/domino/rui/Default.aspx"; //提交的URL地址
  2. static var return_data:String;
  3. var strname:String;
  4. var strpwd:String;
  5. var cls:boolean=false;
  6. var xx:Rect = Rect (20, 10, 150, 100);
  7. function OnGUI() {
  8. if(cls)
  9. xx = GUI.Window(1, xx, windowjj, "Window");
  10. GUI.Label(Rect(10,10,80,20),"UserName:");
  11. GUI.Label(Rect(10,30,80,20),"Userpass:");
  12. strname=GUI.TextField(Rect(90,10,100,20),strname);
  13. strpwd=GUI.PasswordField(Rect(90,30,100,20),strpwd,"*"[0],25);
  14. //same as above, but for password
  15. if ( GUI.Button ( Rect (60, 60, 100, 20) , "Login" ) ){ //just a button
  16. Login();
  17. }
  18. }
  19. function windowjj(windowID : int){
  20. GUI.Label(Rect(55,25,50,20),return_data);
  21. if(GUI.Button(Rect(50,55,50,20),"Close")) cls=false;//
  22. }
  23. function Login() {
  24. var form = new WWWForm(); //创建一个WWWForm对象。
  25. form.AddField( "name2", strname );
  26. form.AddField("pwd",strpwd);
  27. var w:WWW=new WWW(URL,form);
  28. yield w; //we wait for the form to check the PHP file, so our game dont just hang
  29. cls=true;
  30. if (w.error != null) {
  31. //if there is an error, tell us
  32. return_data=w.error;
  33. } else {
  34. return_data=w.text;
  35. w.Dispose(); //clear our form in game
  36. }
  37. }
复制代码


4. 此代码放在主相机上。

5.最后在网上搜一个crossdomain.xml文件,自己写也行,把它放在挂有Asp.net网站的根目录下,这样就大功告成了.



6,导入到IPhone手机里也成功访问到数据库.

你可能感兴趣的:(Unity技术文章)