通過查找資料,Unity3D中C#和js要相互調用彼此的方法,js文件必須放在"Standard Assets"、 "Pro Standard Assets" 和 "Plugins"這三個文件夾中的任意一個。
在Scripts文件夾新建一個C#腳本 csTest :
public class csTest : MonoBehaviour { void Start () { jsTest js1 = gameObject.GetComponent<jsTest>(); js1.PrintJS("C#類中調用 "); } public void PrintCS (string str) { print(str+":C#方法被調用"); } }
在Standard Assets新建一個js腳本jsTest:
function Start(){ var cs1=gameObject.GetComponent("csTest"); cs1.PrintCS("從js中調用 "); } function PrintJS (str) { print(str+": js方法被調用"); }
然將腳本都掛載到主攝像機上
C#和js腳本都是通過主攝像機這個游戲對象以組件的方式來獲取的,也可以放在其他游戲對象上或者新建一個空的游戲對象。
運行游戲,查看控制台的打印信息。
相互調用成功!
js腳本為什么要放到這三個文件夾中?因為javascript腳本和C#腳本是不會編譯到一起的。
查看官網的文檔關於腳本編譯順序:http://docs.unity3d.com/Manual/ScriptCompileOrderFolders.html
The phases of compilation are as follows:-
Phase 1: Runtime scripts in folders called Standard Assets, Pro Standard Assets and Plugins.
Phase 2: Editor scripts in folders called Standard Assets/Editor, Pro Standard Assets/Editor and Plugins/Editor.
Phase 3: All other scripts that are not inside a folder called Editor.
Phase 4: All remaining scripts (ie, the ones that are inside a folder called Editor).