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文件夹下

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/81938554