unity3d 中JavaScript指令碼和C#指令碼的相互呼叫
阿新 • • 發佈:2018-12-26
本人親測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資料夾下