1. 程式人生 > >unity3d 中JavaScript指令碼和C#指令碼的相互呼叫

unity3d 中JavaScript指令碼和C#指令碼的相互呼叫

本人親測unityd5.56版本,開啟Unity在Project檢視下新建資料夾Standard Assets。新建JavaScript指令碼:testJs,C#指令碼testCs.

testJs程式碼如下:

  1. function OnGUI()
  2.     {   
  3.         //繪製button
  4.         if(GUI.Button(Rect(25,25,100,30),"JS Call CS" ))
  5.         {
  6.         //獲取物件身上CS指令碼
  7.             var a = this.GetComponent("testCs");
  8.        //呼叫CS指令碼的Print Test()方法
  9.             (a as testCs).PrintTest();
  10.         }
  11.     }
  12.     function testPrint()
  13.     {
  14.         print("CS Call JS");
  15.     }

testCs程式碼如下: 

  1. public void OnGUI ()
  2.     {
  3.        //繪製button
  4.         if (GUI.Button (new Rect (25, 70, 100, 30), "CS Call JS")) {
  5.            //獲取物件身上的JS指令碼
  6.             testJs c = (testJs)gameObject.GetComponent<testJs> ();
  7.            //呼叫JS指令碼的test Print()方法
  8.             c.testPrint ();
  9.         }
  10.     }
  11.     public void PrintTest ()
  12.     {
  13.         print ("JS Call CS");
  14.     }

 Standard Assets資料夾裡的指令碼是會先編譯的,把C#指令碼呼叫Js方法

  1.  testJs c = (testJs)gameObject.GetComponent<testJs> ();
  2.  c.testPrint ();     註釋掉,然後放到Standard Assets資料夾下

        testCs指令碼放到Assets 資料夾下,然後testCs指令碼和testJs指令碼掛載在同一個遊戲物件身上,執行

就會列印JS Call CS.    testJs呼叫testCs方法PrintTest()方法成功。

        同樣testJs

      testCs放到Assets資料夾下,執行

就會列印CS Call JS.   testCs呼叫testJs方法testPrint()方法成功。

  1.  var a = this.GetComponent("testCs");
  2.  (a as testCs).PrintTest();  註釋掉,然後放到Standard Assets資料夾下