當前位置:編程學習大全網 - 源碼下載 - 如何用unity3d編寫javascript

如何用unity3d編寫javascript

Unity中的JS,也稱UnityScript,和基於瀏覽器的JS有比較大的區別,因為UnityScript是基於Mono的.net 的IL語言規範,CLR運行環境(Mono虛擬機)上設計的語言。

0.基本概念:

Unity3d中的腳本可以與遊戲對象鏈接,變量數值的修改以及實時預覽腳本修改後的遊戲效果,節省了很多腳本調整和調試的時間,提高了開發效率。

簡單的項目和Unity中的大量例子和腳本資源包都是用JS。商業項目基本都用C#,因為C#和C/C++交互方便,豐富的數據結構和面向對象的架構利於大型程序的編寫,很多強大的第三方插件是用C#開發的,方便工作流程。

編譯過程:

UnityScript運行環境使用Mono 的.NET Framework。實際上,UnityScript是用Boo實現的,Boo是運行在Mono虛擬機上的壹種語言,並且編譯成本機代碼。JavasScript很多典型的運行環境如String和Math庫由Mono提供。妳也就知道了為什麽UnityScript中方法名要大寫了,因為要與Mono中相同。

Unity中的腳本和傳統的解釋型(JIT解釋)語言不同,都是需要經過編譯的,因此速度都壹樣快。

這三種語言的代碼最後都會被編譯執行,而且腳本可以互相訪問。

庫的調用:

Unity的腳本基於Mono的.net平臺上運行,腳本都可以使用.net庫,為xml,數據庫,正則表達式提供了良好的解決方案。

Unity中js想調用mono的.net庫,直接import即可。

import System;

import System.IO;

否則,妳帶指定完整的命名空間來調用函數,如System.IO.File.Open(),而不是File.Open()。

1.基本類型和語句:

1)數據類型:

數值類型:char,byte,sbyte;short, ushort, int, uint, long, ulong; float,double; decimal.

布爾值:boolean

字符串:String,[index]符號

字符串[0]是字符串取下標為0的字符。

var s: String = "Whatever_it_may_be";

s =s.Replace("_"[0], " "[0]); // replace all the underscoreswith spaces

2)變量聲明:

變量必須先聲明[必須](編譯緣故,且聲明類型有利於減少太多常量,避免內存泄露發生),可以定義類型[可選]:

var playerName:String;

函數的參數也要聲明類型:

function Test( playerName:String, baseInfo:Object )

{

}

如果聲明時候定義或賦值了類型,那麽不能再改變類型,除非聲明時候不定義類型。

var a= "test";

a =5;// 報錯

var a;

a ="test";

a =5;//正確

變量前面可以加public,protected, private來修飾;不寫默認是public的,public的變量可以在Inspector視圖中查看和編輯。

3)數組:

內建自定義數組(快功能簡單):

var values : int[] = {1,2,3};

轉換到Array數組(需要對數組處理),var arr = new Array(values);

Array對象數組(慢動態增長排序合並功能):

var arr = new Array(); arr.Push("good");

轉換到內建數組(需要比較高的性能時候),var bArray : int[] = arr.ToBuiltin(int);

4)鏈表和泛型:

UnityScript可以使用泛型,所以當用到動態大小的數組時,最好用List來替代Array。基本上就沒有什麽理由要用到Array了,List更快並且功能更多。如果妳需要混合類型的數組,妳可以用Object List。UnityScript中泛型的語法與C#中接近,除了要加壹個額外的“.”符號在“<>”之前。如C#中的"varmyList = new List<int>();"在UnityScript中對應的寫法為:"var myList = new List.<int>();"。

5)運算符和表達式:

和C壹樣。

6)語句:

每行必須寫分號; 比C多了for in 用於遍歷對象元素,for(var i:int = 0; i < 10; i++)。

switch可以使用String變量。

2.函數

聲明規則:

function函數名(參數1:參數類型, 參數2:參數類型...):返回值類型

{

}

unityScript中的函數可以視為Function類型對象,可以像變量壹樣進行賦值比較等操作。

不能寫匿名函數。

Math需要用Mathf。

3.類(DOM js中沒有類):

在Unity裏,壹個js文件就是壹個類,unity引擎會為js文件自動生成壹個類。

對於UnityScript腳本,Unity編譯該文件時會自動的為腳本添加壹個與腳本文件名相同的類,並自動地繼承於MonoBehaviour。但對於C#或Boo,則需要在腳本中顯式的寫出類名和繼承關系。要創建不繼承自MonoBehaviour的類,用C#語言,或者從外部添加js腳本資源(就可以自己直接new對象出來了)。

//SayHello.js

#pragma strict // 嚴格類型檢測,盡早生成錯誤,禁用動態類型,強制用靜態類型(強類型)

function sayHello()

{

}

等價於C#中:

#pragma strict

public class SayHello extends MonoBehaviour

{

function sayHello()

{

}

}

但是,妳可以在同壹個文件中聲明多個類,尤其是當妳需要使用壹些輔助工具類時非常有用,壹般這種輔助類沒有繼承自MonoBehaviour。

class ButtonState {

var currentState : int;

var offset : Vector2;

}

如果妳在壹個文件中聲明了MonoBehaviour的子類,但類名與文件名不匹配的話,即使是大小寫不壹致,妳也會碰到麻煩。

壹定要理解,當妳在js文件中編寫行為腳本是,妳實際上在編寫壹個類:

a) 類及其對象:文件名就是類名,如果文件名是foo.js,妳就可以在其他地方以var x = new foo()的格式進行調用;

b)類的方法和預定義方法:有壹些特定的方法是實現系統預先定義的壹些事件處理器,如Start、FixedUpdate等。任何事件中,聲明的壹個函數就是這個文件所代表的類的壹個方法。

c) 類的屬性:文件中在函數定義之外編寫的代碼都在該類的範圍之內執行,聲明的變量也是該類的成員變量。類中的靜態函數、變量本質上是類的方法與屬性。

實例:

/*whenyou drag the behavior onto a gameobject, these values will be visible andeditable

*/

public name : String;

/*otherscripts which have a reference to this object (e.g. if they're attached to thesame object) can see public functions

*/

publicage : int;

/*privatemembers are NOT visible to other scripts, even if they have a reference to thisobject

*/

private favoriteColor : Color;

/*youcan assign a value to bestFriend by dragging a gameObject with an attached copyof the foo behavior to this property. This will give you access to bestFriend'spublic methods and members

*/

public bestFriend : foo;

/*this function will be called every frame by Unity, so it's actually an eventhandler

*/

function Update(){

/*transform is a property inherited from thegameObject the behavior is attached to*/

var t = transform;

}

function Bar(){

// this is just a function, if you don't callit yourself, it will never do anything

}

4.繼承

Unity裏需要extends關鍵字:

class MyHello extends Hello

{

}

DOM js中用prototype裏的bind()方法。

Unityjs裏面還提供了虛擬函數。

類的繼承也是不同的。在JavaScript和C#中,方法是隱型並且不可重載,除非方法聲明中添加虛擬關鍵字。不同的是C#只重載那些包含重載關鍵字override的方法。而JavaScript不需要關鍵詞,只要重載類方法就可以覆蓋,其它的都可繼承得到。

//Foo.js

var foo = "hello, world";

function doEet () {

// does nothing, intended to be overridden

}

將會生成:

//Foo.js

import UnityEngine;

classFoo extends MonoBehaviour {

public var foo = "hello, world";

public function doEet () {

// does nothing, intended to be overridden

}

}

子類寫法:

//PrintingFoo.js

class PrintingFoo extends Foo {

function doEet() {

print( foo );

}

}

創建虛函數:

classFoo

{

virtual function DoSomething ()

{

Debug.Log("from baseclass");

}

}

//SubFoo.js

class SubFoo extends Foo

{

virtual function DoSomething()

{

Debug.Log("from subclass");

}

}

//Elsewhere

varfoo : Foo = new SubFoo();

foo.DoSomething();//printsfrom sub class

如果妳要調用父類的方法,用關鍵字super。示例如下:

class SubFoo extends Foo

{

virtual function DoSomething()

{

super.DoSomething();// 不是虛函數,應該不需要super修飾就可以直接調用。

Debug.Log("from sub class");

}

}

//Elsewhere

varfoo : Foo = new SubFoo();

foo.DoSomething();//prints"from base class" and "from sub class"

類間通信:Use-a方式(關聯關系)比繼承耦合度底得多,易於修改維護

/*Foo.js */

varbar : Bar;

function Start(){

bar = gameObject.GetComponent(Bar);

}

function doEet(){

// do my own thing

if( bar ){

bar.doEet();

}

}

/*Bar.js */

function doEet(){

// do something special

}

5.對象

Unity中不壹定可以用new 創建對象(普通類可以,特殊類不行,各種腳本都壹樣)。特殊類:用編輯器工程視圖右鍵或者組件Create js 或者C#的類都是繼承自MonoBehaviour類,對這種類型的類不能new出來壹個對象,原因是Unity會為這種類自動創建對象,並調用被重載的方法。

使得用Unity非常有趣的壹件事是,它的類采用了非常自由的mixin策略。通常妳可以非常快速簡單的查到妳所需要的類。最通用的壹個例子是Transform類,對於妳正在處理的壹個對象,所有被附加到該對象的相關聯的類,都可以簡單快速的獲取它的屬性和方法。

比如,典型的動作就是妳會訪問名叫"transform"的變量,它代表與該對象關聯的Transform類的實例。如果妳需要相關的位置坐標,就訪問transform.position(壹個 Vector3對象);如果妳需要它的GameObject,就訪問transform.gameObject;如果妳需要它的渲染器,就訪問transform.renderer。等等。壹般如果妳壹個對象的主要屬性,妳就可以快速獲取該對象所有其他的屬性。

6.js和C#單向通信,不能雙向通信,因為編譯問題

js訪問C#腳本組件:

//createa 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

}

//rendertext and other GUI elements to the screen

function OnGUI()

{

//render the CSharp1 'message' variable

GUI.Label(new Rect(10,30,500,20),csScript.message);

}

C#訪問js腳本組件:

using UnityEngine;

using System.Collections;

public class CSharp2 : MonoBehaviour

{

//create a variable to access the JavaScriptscript

private JS1 jsScript;

void Awake()

{

//Get the JavaScript component

jsScript = this.GetComponent<JS1>();//Don'tforget to place the 'JS1' file inside the 'Standard Assets' folder

}

//render text and other GUI elements to thescreen

void OnGUI()

{

//render the JS1 'message' variable

GUI.Label(newRect(10,10,300,20),jsScript.message);

}

}

7.使用第三方庫:

第三方.NET庫如XML-RPC可以以新建資源Asset的方式引入。

8.調試

可以用print函數,Log()函數或者Debug.Log(),想設置斷點,用Debug.Break()函數。

print() 函數將會生成消息,並輸出到狀態欄及控制臺中,但僅限MonoBehavioour類範圍內。

更好的辦法是使用Debug.Log("insert messagehere");,該方法到處都可使用。還可用Debug.LogWarning 和 Debug.LogError生成警告和錯誤消息。

Debug.Break(); 可以將遊戲暫停在壹個精確的點。當壹種特定的情條件發生時,如果妳想檢查對象的狀態的時候,這個特性非常有用。

開發環境運行項目時,編輯界面也是完全實時更新的,妳可以查看對象實例的內部狀態。

  • 上一篇:求永恒之塔護法宏詳細設置
  • 下一篇:如何做EDM郵件營銷
  • copyright 2024編程學習大全網