Unity3D支持三种脚本语言,javaScript、C#、Bool,Bool这种语言我不熟悉、不做评论,下面就说说javaScript与C#,我本人是搞C++,javaScript与C#这二种语言以前都没有接触过,通过这段时间对Unity3D的了解,我个人比较偏向与C#,最主要的就是C#的 delegate,通过C#的delegate可以调用其他脚本,而javaScript只能通过sendMessage这种方式,Unity3D是C++写的,所以我估计SendMessage的方式应该是MFC的方式是一样的,从运行速度、和代码的结构上来讲C#都是更好的选择。
当然也不排斥javaScript,不过我是真心的不喜欢这种弱类型的语言。下面是Delegate和SendMessage之间的优化性能差距测试
- using UnityEngine;
- using System.Collections;
- /// <summary>
- /// Delegate basic.
- /// just test Delegate && SendMessage ..
- ///
- /// By Chiuan 2012.8
- /// </summary>
- public class DelegateBasic : MonoBehaviour {
- //define my delegate statement.
- public delegate void MyDelegate(string arg1);
- //create my delegate object
- public MyDelegate myDelegate;
- //need some values to debug time spent.
- bool isStart;
- float timeStart;
- int count;
- bool isStartSendMessage;
- // Use this for initialization
- void Start () {
- myDelegate += myFunciton1;
- //myDelegate += myFunciton2;
- }
- // Update is called once per frame
- void Update () {
- if(isStart )
- {
- isStart = false;
- count = 0;
- timeStart = Time.realtimeSinceStartup;
- Debug.Log("Start = " + timeStart );
- for(int i= 0; i< 50000;i++)
- {
- if(myDelegate != null) myDelegate("");
- }
- }
- if(isStartSendMessage)
- {
- isStartSendMessage = false;
- count = 0;
- timeStart = Time.realtimeSinceStartup;
- Debug.Log("Start = " + timeStart );
- for(int i= 0; i< 50000;i++)
- {
- this.gameObject.SendMessage("myFunciton1","",SendMessageOptions.DontRequireReceiver );
- }
- }
- }
- void OnGUI()
- {
- if(GUILayout.Button("INVOKE Delegate"))
- {
- isStart = true;
- }
- if(GUILayout.Button("SendMessage"))
- {
- isStartSendMessage = true;
- }
- }
- void myFunciton1(string s)
- {
- count++;
- if(count == 50000)
- {
- Debug.Log("End = " + Time.realtimeSinceStartup );
- Debug.Log("Time Spent = " + ( Time.realtimeSinceStartup - timeStart ) );
- }
- }
- void myFunciton2(string s)
- {
- //Debug.Log("myFunciton2 " + s);
- }
- }