本人亲测unityd5.56版本,打开Unity在Project视图下新建文件夹Standard Assets。新建JavaScript脚本:testJs,C#脚本testCs.
testJs代码如下:
- function OnGUI()
- {
- //绘制button
- if(GUI.Button(Rect(25,25,100,30),"JS Call CS" ))
- {
- //获取对象身上CS脚本
- var a = this.GetComponent("testCs");
- //调用CS脚本的Print Test()方法
- (a as testCs).PrintTest();
- }
- }
- function testPrint()
- {
- print("CS Call JS");
- }
testCs代码如下:
- public void OnGUI ()
- {
- //绘制button
- if (GUI.Button (new Rect (25, 70, 100, 30), "CS Call JS")) {
- //获取对象身上的JS脚本
- testJs c = (testJs)gameObject.GetComponent<testJs> ();
- //调用JS脚本的test Print()方法
- c.testPrint ();
- }
- }
- public void PrintTest ()
- {
- print ("JS Call CS");
- }
Standard Assets文件夹里的脚本是会先编译的,把C#脚本调用Js方法
- testJs c = (testJs)gameObject.GetComponent<testJs> ();
- c.testPrint (); 注释掉,然后放到Standard Assets文件夹下
testCs脚本放到Assets 文件夹下,然后testCs脚本和testJs脚本挂载在同一个游戏对象身上,运行
就会打印JS Call CS. testJs调用testCs方法PrintTest()方法成功。
同样testJs
testCs放到Assets文件夹下,运行
就会打印CS Call JS. testCs调用testJs方法testPrint()方法成功。
- var a = this.GetComponent("testCs");
- (a as testCs).PrintTest(); 注释掉,然后放到Standard Assets文件夹下