您的位置:首页 > 移动开发 > Unity3D

Unity3D: JavaScript->C# 或 C#->JavaScript的调用

2014-02-24 17:11 429 查看
在进行Unity3D 编程时,有些情况下,我们需要访问另一个不是我们正在使用的编程语言的脚本。虽然强烈推荐将所有脚本转换成一种,但是知道如何从一个JavaScript类访问一个C#脚本及反过来的情况 是很有用的。

首先要做的是将脚本放在project的正确目录。你要访问的脚本必须要放在Standard Assets
或者 Plugins目录(注:本人Unity4.2测试的时候,Unity是不允许新建 Plugins 目录的)。其他脚本放在这些目录的外面。完了之后,就可以像其他Component一样调用GetComponent() 方法。这里是一个JavaScript 例子:

//create a variable to access the C# script  
private var csScript : CSharp1;  
   
function Awake()  
{  
    //Get the CSharp Script  
    csScript = this.GetComponent("CSharp1"); //Don't forget to place the 'CSharp1' file inside the 'Standard Assets' folder  
}  
   
//...


C# 例子

using UnityEngine;  
using System.Collections;  
   
public class CSharp2 : MonoBehaviour   
{  
    //create a variable to access the JavaScript script  
    private JS1 jsScript;   
   
    void Awake()  
    {  
        //Get the JavaScript component  
        jsScript = this.GetComponent<JS1>(); //Don't forget to place the 'JS1' file inside the 'Standard Assets' folder  
    }  
//...  
}


这些就是如何做的了。没有办法同时地获取C#和JavaScript的,因为其中一个脚本必须在Standard Assets 或者 Plugins 目录。这些目录中的脚本首先被编译,意味着这些脚本不能访问外面的脚本了,因为他们还没有编译。

译文原处
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: