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);
- }
-
-
- }