admin 管理员组

文章数量: 887019


2024年2月27日发(作者:judge同义词组)

12-7-10Unity3d的Javascript入门教程_Developer_百度空间Developer我在奔跑, 我在狂笑,我还很年轻~Unity3d的Javascript入门教程2011-10-20 19:04VARIABLES (变量) Let's think of a variable as acontainer that holds something. The Value you set the variable tobe is what it becomes.我们来想想,变量就像一个临时存贮某种东西的容器,你给它设置什么值,它就会变成什么

You can choose to name a variable anything you wish, as long as itcontains no spaces, starts with a letter(preferably lower case),contains only letters, numbers, or underscores, and is not areserved keyword.

你可以给你的变量命你想要的名字.以小写字母开头.包括使用字母,数字,下划线.

Use the keyword 'var' to create a variable. Let's call our firstone 'box'.输入"var"可以创建一个变量,让我们调用我们的第一个叫"box"的变量.Code:(代码)var box;

There you go; you've declared your first variable! If you'rewondering about the semicolon at the end, statements(commands) inJavascript must end in a semicolon.

Javascript中在申明一个变量时要以";"结尾.

iPhone programmers, if you declare a variable without setting it toa value, you must state what type the variable

is, in this caseString. Common types include String, int, float, boolean, andArray.如果是IPhone程序员,在声明一个变量时一定要指明变量的类型.在这个案例中是字符串型,一般情况下变量类型包括字符串型,整型,布尔型和阵列.Note that proper capitalization isnecessary!

var box :String;

Of course, our box is empty, so let's set it to a value by addingthe following line:当然我们的box是空的,因此我增加以代码给它一个值.Code:box ="apple";

Now our box contains a text string (variable type), which happensto be "apple".

现在我们的box包含字符型.它叫"apple".

Note that you can declare your variable and set it to a value inthe same statement:也可以这样写/184367426/item/c9490992653d5efd291647d91/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间Code:var box ="apple";

But once it's declared, you can't declare itagain.

但是你一旦申明一个变量就不能重复申明同一个变量You can, however, change it to another value (as long as the newvalue is the same type as the original).那么你如何改变成另一个值呢?Code:box ="orange";

In addition to text strings, variables can hold numbers:除了字符串,你也可以存贮数字类型Code:var number =10;

This is an integer (int), which means whole nodecimal places.

这是整型(用int表示),它是个整数类型,没有小数点.

But we could also do a floating point number (float), which hasdecimal places:我们也能用浮点型(用float表示)Code: var myFloat =10.5;

Variables can also contain booleans. A boolean is simply atrue/false value:变量也能包括布尔型(用boolean表示), 布尔型只有true/false(真或假)两个值.Code:var gameOver =true;

We'll discuss these more later.

稍后我们会有更多的讨论.

Notice that a variable can normally only contain one thing at atime. But we can make a variable that contains multiple things, bycreating an array:注意,通常情况下一个变量只包含一种东西,我们也可以让一个变量包含更多的内容我们就通过创建一个阵列来实现.Code:var applePie = Array("apple", "brown sugar","butter", "pie crust");

This variable contains everything you need to make an applepie!

这个变量包含了制作一个的所以有东西

If we wanted to view the contents of applePie, we could output itto the Unity console using the Debug command.如果我们想看看苹果派内容,可以通过Debug命令将它们输出到Unity控制台.Add this line to the code above:添加这行代码Code:/184367426/item/c9490992653d5efd291647d92/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间(applePie);

On play, the console should display: apple,brownsugar,butter,pie crust

按下播放钮,控制台将显示:apple,brown sugar,butter,piecrust

To access a single element (item) from an array, we can access itthru its index (position in array). This may seem confusing, butindexes start at 0. So index 0 is actually the first element in thearray.我们可以通过它的序号来访问它的元素,这看起来似乎有点混乱,不过由于序号是从0开始的,实际上0是阵列的第一个元素.Code:var applePie = Array("apple", "brown sugar","butter", "pie crust");

var item1 = applePie[0];

(item1);

You can actually use indexing with Strings as well. The followingcode displays the first character of "hello", theletter 'h':实际上你也可以用索引序号来访问字符.比如下面代码就显示"hello"的第一个字母"h"。Code:var myString ="hello";

(myString[0]);

Now lets alter our variables in other ways.

现在我们来改变一下我们的变量We can add variables:Code:var number1 = 10;

var number2 = 11;

var total = number1 + number2;

(total);

If you add an int (integer) to a float (floating point number) theresult becomes a float: 如果我们给一个整型变量增加一个浮点型,结果就会变成一个浮点型变量Code:var number1 = 100;

var total = number1 + 1.5;

(total);

Obviously, we can also subtract/divide/multiply ints andfloats.

显然我们也可以用减/除/剩整型和浮点型变量

Less obvious, we can also 'add' strings. This merges themtogether:可以通过“add”(加)这个字符串把它们结合在一起。

Code:var string1 ="apple";

var string2 = "cider";

var combo = string1 + string2;

/184367426/item/c9490992653d5efd291647d93/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间(combo);

If we add a number to a string the result becomes astring.

如果我们把一个数字加到一个字符串类型上结果也会变成字符串型。

We can also multiply strings.我们还可以对字符串使用剩的方式,使它倍增。

Code:var greeting ="howdy";

(greeting * 3);

Unfortunately, we can't divide or subtract strings. There are waysto split strings and remove parts of strings, but that is a moreadvanced topic.不幸的事,我们不能对字符串型进行减或除的操作,有专门对字符串进行分离和删除的方法,当然这是高级话题。

Let's wrap up our discussion on variables with incrementing numbers(changing their value by a set amount).

下面我们来看看怎样让数值递增First, declare a variable and set it to 1:首先申明一个变量,设置它的值为了:Code:var number =1;

We can increment numbers various ways.我们能用不同的方式来增加这个数Code:number = number +1;

The above adds 1 to our number, and it becomes2.

上面是对原有的数加上1.其结果变成2.

But programmers are lazy, and decided this was too long. So theyabbreviated it to:可是程序员可都要省事,可能这样定觉得太长了,所以要写短一点Code:number +=1;

This is simply shorthand for number = number +1;

可以简单地缩短成number=number+1;

But guess what? Lazy programmers decided even THIS was too long,and shortened it to:可是你猜怎么着,懒惰的程序员还是觉得它太长了.于是就缩短成这样: Code:number++;

Use whichever makes most sense to you, they all do the same thing!But note that if you choose to increment by

/184367426/item/c9490992653d5efd291647d94/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间a value other than 1,++ won't work. ++ is shorthand for += 1only.

这些方法的结果都是一样的,但值得注意的事增加指定的值"++"是不可以的."++"只表示"+=1"

You can also do the same with subtraction:同样道理,你也可以写成"--"Code:number--;

But for division and multiplication, you must use one of the longerforms:但是乘除就不能那样了Code:number = number/2;

number *= 2;

Note that an asterisk means multiply, a slash means divide.

Enumeration (枚举)Enum allows you to create a collection of integer based constantvalues. While working with Javascript variables instead of creatingindividual variable for constants you must use Javascript enumvariable to store integer based (枚举数型)允许你创建一个整数集合. Javascript enum type variables and their valuesprovide the systematic code pattern as well as readability andunderstanding for the code. You can easily get the integer valueassociated with the named enum type 的枚举类变量和它们的值提供了代码模式,以便它的可读性和对代码的理解.你可以轻易地一个整数值Code:enum myEnum { myName1, myName2, myName3}

Enum is an enumeration type collection that stores the items withcomma separation "," and its correspondinginteger value separated with colon ":".Code:enum AiState { Sleeping, Idling, Chasing,Dying }function Update (){ varstate :AiState; //first example var state = ng; print (state);

var curState :AiState; // secondexample curState = ; switch (curState) { case ng: print ("aiState issleeping"); break; case : print ("aiState is idling");break;

default: break;/184367426/item/c9490992653d5efd291647d95/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间 }}

Note: The Enumeration should be declared outside a function注意:枚举类应该在函数外面申明. IF STATEMENTS (if语句)

If statements are conditional statements. If a condition evaluatesas true, do something.

We can do a comparison of two values by using two equal signs,==

"number == 10" evaluates as true if our number variable equals 10,otherwise it evaluates as false.

if语句是条件语句,如果条件满足为真,执行.我们可以用"=="双等号对两个值进行比较,比如"number==10"当条件为真时变量number等于10,反之为假.Note: it's important to remember to use two equal signs whencomparing variables/values, but one equal sign when setting avariable to a value!

注意.重要的事要记住比较变量与值时用双等号,而不是一个等号.

The following creates a variable and sets it to true, checks to seeif the variable equals true, and if so prints a text下面创建一个变量,设置为真,检测为真时打印后面的文字.string to the console:Code:var gameStarted =true;

if (gameStarted == true)

("Game hasstarted");

The above is actually redundant, since our variable 'gameStarted'is a boolean. There is no reason to check "if true equals true",just check "if true":上面这些是多此一举,由于我们的变量gameStarted是布尔型,没理由检测是否为"等于'=='"真Code:var gameStarted =true;

if (gameStarted)

("Game hasstarted");

If you're wondering why I didn't put a semicolon behind if(gameStarted), it's because technically it is only the first halfof the statement. I could have written it like so:你可能觉得奇怪.为什么我不在if后面放上";"分号呢,那是因为理论上说它只是语句的第一部分.我可以写成这样:Code:if (gameStarted) ("Game hasstarted");

I could have also written it this way:还能用这种方法写:/184367426/item/c9490992653d5efd291647d96/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间Code:if (gameStarted){

("Game hasstarted");

}

Those brackets represent a block of code, and tell the if statementto execute anything if the condition istrue!

花括号代表一个代码模块,告诉if语句如条件为真则执行模块的代码.

When if contains only one statement to execute, the brackets areoptional. But if it contains more than one statement, you MUST usethe brackets! Note that semicolons are not needed afterbrackets当if条件句下只有一行代码,花括号可以不要,但如果是多行就是必须的.

Code:var gameStarted =false;

If (gameStarted == false){

gameStarted =true;

("I just started thegame");

}

Read the second line of code above. Remember those lazyprogrammers? They don't want to writeCode:if (gameStarted == false)阅读以上代码,记得那些懒惰的程序员吗,他们不想这样写代码:if (gameStarted == false)

When they can just write:他们这样写:Code:If (notgameStarted)

But you know what? Why write 'not' when I can shorten that too?还可以这样写:Code:if (!gameStarted)

Yes, an exclamation point means 'not' to lazyprogrammers!

好吧,一个惊叹号对于一个懒惰的程序来说它的意思是"否"

You can also combine this with equals, where it means "notequals":你也可以把它与"="号合在起用,表示"不等于"Code:var answer = 1;

if (answer != 42) ("Wrongquestion!");

/184367426/item/c9490992653d5efd291647d97/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间You can also check for greater than or less than:你也能检测更大或更小的数:Code:var age = 18;

if (age > 18)

("oldenough");

else if (age < 18)

("jailbait");

else

("exactly18");

Notice the 'else if' and 'else' keywords? if the first if statementcondition fails (evaluates as false), it then checks the conditionunder else if. If that one fails, it will check the next else if(if one is available), and finally if all conditions fail, itexecutes the statement under else. Again, if the 'if', 'else if',or 'else' statements contain more than one

statement, each block ofcode must be separated by brackets.

注意:"else if"和"else"关键词.如果第一个条件失败(执行为假),那么它就检测elseif下的条件,如果还是失败的,就执行else下面的条件,依此往复."if","elseif","else"语句可以包括多个语句,每个代码模块都须由花括号分开.

You can also check for multiple conditions in a singlestatement:你也可以在一条语句中检测多个条件:Code:if (age >= 21&& sex =="female")

buyDrink =true;

Above, we introduced greater than or equal to >= andthe AND operator, which is two ampersand characters:&&.上面我对多个条件用>=及&&表和If both conditions are true, the statement is executed. If even oneis false, the statement is not.

如果两个条件都为真,语句执行,如果有一个为假,则语句不执行

推荐Note: if you want to run the above code, remember to createvariables for age (int), sex (String), and buyDrink(boolean) first!6 Code:if (engine == "Unity" || developer =="friend")

buyGame = true;

Above, we used the OR operator, which is two pipe characters: ||.If either condition is true, the statement isexecuted. If both are false, the statement isnot.

Note: if you want to run the above code, remember to createvariables for engine (String), developer (String), andbuyGame (boolean) first!

/184367426/item/c9490992653d5efd291647d98/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间If can also be used with the keyword 'in'. This is generally usedwith Arrays:Code:var names = Array("max", "rick", "joe");

if ("joe" in names) ("Found Joe!");

SWITCH / CASE STATEMENTSThese statements allow you to take a single variable and performmultiple operations depending upon what thatvariablecontains. Here is a simple example:Code:switch(somevariable){ case"A": somefunction(); break;

case"B": someotherfunction(); break;

default: break;}

The switch statement above takes a variable called "somevariable"and performs one of three events depending

upon the valueof the variable. If the variable contains A then the somefunction()function will be called. If the variable contains

B, then thesomeotherfunction() function will be called, otherwise the defaultoperation is used. The break statement after each case willstop the script at that point, so cases are useful for specificscenarios.

7 LOOPING

Looping allows you to repeat commands a certain amount of times,usually until some condition is met.

What if you wanted to increment a number and display the results tothe console?

You could do it this way:Code:/184367426/item/c9490992653d5efd291647d99/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间var number = 0;

number += 1;

(number);

number += 1;

(number);

number += 1;

(number);

And but this is redundant, and there is nothing lazyprogrammers hate more than rewriting the same codeover and over!

So use a For Loop:Code:var number = 0;

for (i=1; i<=10; i++){

number +=1;

(number);

}

Okay, that for statement on the second line may look a littleconfusing. But it's pretty simple actually.

i=1 -created a temporary variable i and set it to 1. Note that youdon't need to use var to declare it, it'simplied.

i<=10 -how long to run the loop. In that case,continue to run while i is less than or equal to10.

i++ -how to increment loop. In this case, we are incrementing by 1,so we use the i++, shorthand for i+=1

If we're just printing 1 thru 10, our code above could beshortened. We don't really need the number variable:Code:for (i=1; i<=10; i++)

(i);

Just like if statements, brackets are optional when there is onlyone statement to execute. Talk about beating

We can also count backwards:Code:for (i=10; i>0; i--)

(i);

Or print all even numbers between 1 and 10:

Code:for (i=2; i<=10; i+=2)

(i);8

We could also use a While loop, an alternative to Forstatements.

/184367426/item/c9490992653d5efd291647d910/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间

While executes repeatedly until a condition is :var number = 0;

while (number < 10){

number++;

(number);

}

While loops are most useful when used with booleans. Just make surethe escape condition is eventually met, oryou'll be stuck in an infinite loop and the game will most likelycrash!Code:var playerJumping = true;

var counter = 0;

while (playerJumping){

//do jumpstuff

counter +=1;

if (counter >100) playerJumping = false;

}

("While loop ended");

Notice the fourth line of code above? The one that starts with twoslashes? This means the text afterwards is acomment, and will not be executed. Comments are useful for notinghow your code works for yourself or others,for putting in placeholder text to be replaced later (as above), orfor commenting out sections of your code fordebug purposes.

9 FUNCTIONS

If you thought loops were a time saver, wait until you find outabout functions!

Functions allow you to execute a whole bunch of statements in asingle command.

But lets keep things simple at first. Lets define (create) afunction that simply displays "Hello world" on :function SayHello(){

("Helloworld");

}

/184367426/item/c9490992653d5efd291647d911/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间To execute, or 'call' this function, simply type:Code:SayHello();

Note the parenthesis after our function. They are required, bothwhen we define our function and call it. Also notethat our function name is capitalized. It doesn't have to be, butcapitalizing function names is the norm inUnity.

What if we wanted a function to say different things? We can pass avalue, or argument, to the function:Code:function Say(text){

(text);

}

Above, text is the argument, a temporary variable that can be usedwithin the function only.

iPhone programmers, you should also state what type the argumentis, in this case String.

function Say(text : String){

Now when we call our function, we have to provide anargument:Code:Say("Functions are cool!");

We can also pass variables:Code:var mytext = "I want a pizza";

Say(mytext);

Another useful thing functions can do is return a value. Thefollowing function checks to see if a number is evenand if so it returns true, else it returns false:Code:function EvenNumber(number){ //iPhone programmers, remember to addtype to arg (number : int);

if (number % 2 ==0)

10 // NOTE: % is the mod operator. It gets the remainder of numberdivided by 2

return true;

else

return false;

}

var num = 10;

if ( EvenNumber(num) )

("Number " + num + "is even");

When the return command is executed in a function, the function isimmediately exited (stops running). /184367426/item/c9490992653d5efd291647d912/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间don't have to return a value:Code:function Update(){

if (!gameStarted) return;//exit function

}

The Update() function above is one of the main functions in do not have to call it manually; it gets calledautomatically every frame.

OVERLOADING FUNCTIONS

Functions can be overloaded. Sounds complicated, but it's reallyquite simple. It means you can have multipleversions of a function that handles different types of arguments,or different numbers of arguments.

To handle different types of arguments, simply use the colon : tostate the type of argument being types include String, int, float, boolean, and Array. Notethat proper capitalization is necessary!Code:function PrintType(item : String){

("I'm a string, typeString");

}

function PrintType(item : int){

("I'm an integer,type int");

}

function PrintType(item : float){

("I'm a float, typefloat");

}

function PrintType(item : boolean){

("I'm a boolean, typeboolean");

}

function PrintType(item : Array){

("I'm an array, typeArray");

}

function PrintType(item: GameObject){ //catches everythingelse

("I'm somethingelse");

}

function PrintType(){

("You forgot tosupply an argument!");

}

/184367426/item/c9490992653d5efd291647d913/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间PrintType();

PrintType("hello");

PrintType(true);

12 CLASSES

So variables have different types, such as String and int. But whatif you need a new type that does somethingdifferent?

Classes are simply new types that YOU :class Person{

varname;

varcareer;

}

//Create objects of type Person

var john = Person();

= "John Smith";

= "doctor";

( + " is a " + );

The above class has two class variables, or properties, name andcareer. You access them by typing the name ofthe instance (in this case, John) followed by a period and the nameof the property.

You can also pass arguments when creating instances of a class. Youdo this by creating a constructor, which is aspecial function that is automatically called whenever a newinstance of your class is created. This function has thesame name as your class, and is used to initialize the class:Code:class Animal{

var name;

function Animal(n : String){ //this is the constructor

name = n;

(name + " was born!");

}

}

cat = Animal("Whiskers"); //varkeyword is optional when creating instances!

Classes can have regular functions as well. Class functions aresometimes called methods. Again, you access theseby typing the name of your instance followed by a period and thefunction name (don't forget the parenthesis)./184367426/item/c9490992653d5efd291647d914/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间This is useful for having instances interact with oneanother:Code:class Person{

var name :String;

function Person(n :String){

name = n;

}

function kiss(p :Person){

(name + " kissed " + +"!");

}

}

jenni = Person("Jenni");

bob = Person("Bob");

(bob);13 INHERITANCE

Classes can inherit or extend (add functionality to) another class that gets inherited from is usually calledthe base class or the parent class. The extended class is alsocalled the child class or the derivedclass.

This will be our base class:Code:class Person{

var name :String;

function Person(n : String){//constructor

name = n;

}

function Walk(){ //classfunction

(name + " is walking");

}

}

To extend this class, create a new class with the keyword'extends':Code:class Woman extends Person{

var sex :String;

function Woman(n : String){//constructor

super(n); //calls the original constructor andsets name

sex = "female"; //adds additional functionality to the extendedclass

}

functionWalk(){

(); //calls the original function

("And she is so sexy!"); //adds additional functionalityto the extended class

}

}/184367426/item/c9490992653d5efd291647d915/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间

Note that we can access the base/parent class properties andfunctions by using the keyword 'super'.

If we create an instance of Woman and call function Walk(), boththe parent and child function are called:Code:amanda = Woman("Amanda");

();

14 BUILT IN TYPES ANDPROPERTIES

Now you're probably wondering, "if classes, the types I create, canhave properties and functions, why can't thebuilt in types"?

They do, actually.

To convert an int to a String, use the built-in functionToString():Code:var number = 10;

var text = ng();

To get the length of an Array (or a String), use the built-inproperty length:Code:var animals = Array("cat", "dog", "pig", "dolphin","chimpanzee");

var total = ;

You can use this in a for loop. Add the following two lines to thecode above:Code:for (i=0; i<;i++){

(animals[i]);

}

This displays the contents of our array, one item at atime.

To add an item to an Array, use the function Add():Code:("lemur");

To split a String into an array, use the function Split():Code:var sentence = "The quick brown fox jumped over the lazydog";

var words = (" "[0]);

/184367426/item/c9490992653d5efd291647d916/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间(Array(words));

To get a part of a String, use the function Substring(). Substringtakes two arguments, the starting index and theending index:Code:var sentence = "The quick brown fox jumped over the lazydog";

var firstHalf = ing(0, 19);

(firstHalf);

To capitalize a text string, use the function ToUpper();Code:var mission = "go make cool games!";

( r() );15

As you might expect, there is also a ToLower() :( ("THE END").ToLower() );

ADDITIONAL INFORMATION

Intro to Scripting with Unity

/support/Tutorials/2 -

Intro to Unity Programming on Unify Wiki

/wiki/?title=Programming_Chapter_1_Old

Unity Script Reference Page

/support/documentation/ScriptReference/

MSDN - This is for advanced programmers. Search for JSCRIPT, asit's quite similar to Unity javascript.

/en-us/library/_________________Froggy Math

/~torajima/meganesoft_________________Difference between standard java and unity java script/wiki/?title=Head_First_into_Unity_with_JavaScript#Unity 3d浏览(718)评论转载/184367426/item/c9490992653d5efd291647d917/18

12-7-10Unity3d的Javascript入门教程_Developer_百度空间评论 发布

帮助中心 | 空间客服 | 投诉中心 | 空间协议©2012 /184367426/item/c9490992653d5efd291647d918/18


本文标签: 变量 代码 空间