1 using system.collections;
2 using system.collections.generic;
3 using unityengine;
4 using unityengine.networking;
5 using litjson;
6 using system.io;
7 using system.net;
8
9
10 public class connet : monobehaviour {
11
12 //private arraylist list = new arraylist(5);
13 //private rect rect = new rect(10, 50, 150, 150);
14 //请求地址,写自己的请求地址就行
15 private string url = "http://xxxxxxxxx/apiservlet?method=list";
16 //声明 jsondata litjson 提供的方法
17 jsondata itemdata;
18 //新建 list 存放数据
19 private list database = new list();
20
21 ienumerator start()
22 {
23
24 www getdata = new www(url);
25 yield return getdata;
26
27 if (getdata.error != null)
28 {
29 debug.log(getdata.error);
30 }
31 else
32 {
33 debug.log(getdata.text);
34 }
35 //把请求到的数据转换成 jsondata array 类型,并存储到itemdata里
36 itemdata = jsonmapper.toobject(getdata.text);
37 //debug.log(itemdata);
38 //调用 constructitemdatabase() 函数
39 constructitemdatabase();
40 //测试数据
41 debug.log(database[0].name);
42 }
43 void constructitemdatabase()
44 {
45 //循环取数据
46 for (int i = 0; i < itemdata.count; i++)
47 {
48 //把每个数据都添加到 database 里 要和请求到的json数据对应
49 database.add(new item((int)itemdata[i]["longid"], (int)itemdata[i]["intid"], itemdata[i]["item"].tostring()));
50 }
51 }
52 }
53
54 //新建item类
55 public class item
56 {
57 //定义item内的数据
58 //固定写法 xx{ get; set; }
59 public int id { get; set; }
60 public int intid { get; set; }
61 public string name { get; set; }
62
63 //接收上面的变量
64 public item(int _longid, int _intid, string _name)
65 {
66 id = _longid;
67 intid = _intid;
68 name = _name;
69 }
70 }
密码:1znp
前一段时间一直纠结unity连接数据库请求数据,浪费了不少时间。后来改用http请求,顺利拿到数据,然后就着手于解析数据,就有了这篇文章
如果大家看不懂,这里有一个讲的还是相当详细的