2、網頁向unity發送數據的函數:網頁中用GetUnity().SendMessage(message, "AcceptName", buildingname)函數來調用unity中的函數,此函數的參數message為unity中的物體,AcceptName為物體上的函數,buildingname為傳遞的參數。
網頁中的函數如下:
1 function SayHello(message){//此函數來接收unity中發送出來的message值,並將處理後的數據再發送回unity中
2 jQuery.post('../Unity/javascript/DBhelper.ashx', {id:message}, function(data)
3 {
4 var msg=JSON.parse(data);//將json數據解析
5 var buildingname = msg[0].Building_name;
6 var buildingcategory=msg[0].Building_category;
7 var buildingpic = msg[0].Building_pic;
8 GetUnity().SendMessage(message, "AcceptName", buildingname);//向unity中的message物體上的MyFunction函數發送buildingname值
9 GetUnity().SendMessage(message, "AcceptCategory", buildingcategory);
10
11 GetUnity().SendMessage(message, "AcceptImg", buildingpic);
12 });
13 }
此函數將unity中發送的數據message傳到DBhelper.ashx中,在DBhelper.ashx中將傳遞過來的數據進行查詢等操作,然後再用GetUnity().SendMessage(message, "AcceptName", buildingname)將處理好的數據buildingname傳給unity中的AcceptName函數。
以下是unity中的腳本,可以實現中文,關於中文的實現由於文章有限,在此不再說明,只說明怎樣接收網頁中的數據。
1 var chineseSkin : GUISkin;//在此可以選擇字體,並設置為中文。建議編輯器設為uft-8。
2
3 var buildingname:String;//用來接收從網頁中傳遞過來的buildingname值
4 var buildingcategory:String;//用來接收從網頁中傳遞過來的buildingcategory值
5
6 var buildingpic:Texture2D;//用來接收從網頁中傳遞過來的buildingpic值
7 var windowRect0 = Rect (20, 20, 250, 200);
8 var enable:boolean;
9 function Awake(){
10 enable = false ;
11 }
12 function OnMouseDown () {
13 Application.ExternalCall("SayHello",gameObject.name);// 向網頁中的SayHello函數發送gameObject.name數據
14 enable = true;
15 }
16 function AcceptName(bdname){//用於接收網頁中發送回來的數據
17 buildingname=bdname;
18 }
19 function AcceptCategory(buildingType){//用於接收網頁中發送回來的數據
20 buildingcategory=buildingType;
21 }
22
23 function AcceptImg(img){
24 var www :WWW = new WWW("http://localhost:1166/Unity/images/"+img+"");
25 yield www;
26 buildingpic=www.texture;
27 }
28 function OnGUI(){
29 GUI.skin=chineseSkin;
30 if(enable)
31 {
32 windowRect0 = GUI.Window (0, windowRect0, DoMyWindow, "屬性");
33 }
34 }
35 function DoMyWindow (windowID : int) {
36 GUI.Label(Rect(10,50,80,30),"建築物名字");
37 GUI.TextField(Rect(100,50,100,30),buildingname);
38 GUI.Label(Rect(10,100,80,30),"建築物類型");
39 GUI.TextField(Rect(100,100,100,30),buildingcategory);
40
41 GUI.DrawTexture(Rect(10,150,200,50),buildingpic,ScaleMode.ScaleToFit,true,0);
42 if(GUI.Button(Rect(190,20,50,30),"退出")){
43 enable = false;
44 }
45 GUI.DragWindow (Rect (0,0,10000,10000));
46 }
47 function OnMouseOver(){
48 transform.Rotate(0,Time.deltaTime*100,0,Space.World);
49 }
50 function OnMouseEnter(){
51 renderer.material.color = Color.blue;
52 }
53 function OnMouseExit(){
54 renderer.material.color = Color.yellow;
55 }
這是unity中的腳本,此腳本實現點擊物體,彈出物體的屬性。