Comparison of JavaScript and C # in Unity3d

Source: Internet
Author: User

The first and easiest thing to distinguish is declaring variables and methods.
Script for javascript:

1. private Var cubetransform;

In C #, the same code would be:

1. Private Transform cubetransform;

The same applies to the method, in C #, where a method does not return a value, then his return value is void type, but can be omitted in JavaScript.

The inheritance of classes is also different. In JavaScript and C #, methods are implicit and cannot be overloaded unless the virtual keyword is added to the method declaration. The difference is that C # only overloads those methods that contain overloaded keywords. JavaScript does not require keywords, as long as overloaded class methods can inherit them. Let's look at an example of a JavaScript class inheritance:

1. Class Weapon extends Item

2. {

3.//class members and declarations

4.}

In C #, the same code would be:

1. public class Weapon:item

2. {

3.//class members and declarations

4.}

This is the main difference between the two types of code, in fact he needs to define everything, like executing output code, accessing Gameobject and components, laser projection, etc. There are other different points, such as the keywords that import libraries ("Import" in JavaScript, and "using" in C #), but the differences between these declarations and keywords are easier to understand.

1.//do this:

2. private Var score:int;

3.//instead of this:

4. private VAR score;

======================================================

Using JavaScript to get Gameobject is simple, you just need to call the find () static method and take the name of the desired gameobject as a parameter:

1. private Var pawngo:gameobject;

2. function Awake ()

3. {

4. Pawngo = Gameobject.find ("Pawn");

5.}

In C # is also very similar:

1. Using Unityengine;

2. Using System.Collections;

3.

4. public class Pawngetter:monobehaviour

5. {

6. Private Gameobject Pawngo;

7.

8. void Awake ()

9. {

Pawngo = Gameobject.find ("Pawn");

11.}

12.}

The code is exactly the same regardless of the keyword and format of the two languages (the fourth line of the first code and the eighth line of the second code are the same). The Gameobject.find () method always returns a Gameobject value, regardless of whether the code is strongly typed or weakly typed.

Now, let's see how to get a component on a gameobject. Assuming that the "pawnmover" component is assigned to "Pawn" Gameobject, let's take a look at how to get the "Pawnmover" component using javascript:

1. private Var pawngo:gameobject;

2. private Var pmsc:pawnmover;

3. function Awake ()

4. {

5. Pawngo = Gameobject.find ("Pawn");

6. Pmsc = Pawngo.getcomponent ("Pawnmover");

7.}

Basically, to get the "pawnmover" component, all we need to do is call the Getcomponent () method from the "Pawn" Gameobject and take the name of the required component as an argument. In addition to the name, we can also use the component type as the parameter, but like the above example we have a name on the line. Since JavaScript is a weak type and the return value is a component, we do not need to give the component the result of the Pawnmover class. The same is true in C #:

1. Using Unityengine;

2. Using System.Collections;

3.

4. public class Pawngetter:monobehaviour

5. {

6. Private Gameobject Pawngo;

7. Private Pawnmover pmsc;

8.

9. void Awake ()

10. {

Pawngo = Gameobject.find ("Pawn");

//returns a CS0266 error

Pmsc = Pawngo.getcomponent ("Pawnmover");//<=returns a CS0266 error

//this is the right-to-do it when using C #

Pmsc = pawngo.getcomponent< pawnmover > ();

16.}

17.}

In C # It is not possible to just call the Getcomponent () method and take the name of the component as an argument, so that he can cause error CS0266, that is, C # cannot be converted from one type to another. Because C # is strongly typed, we cannot convert the component type to the Pawnmover type. We need to call a method to pass this type, forcing the Getcomponent () method to return the "Pawnmover" object instead of the component.

======================================================

The third section of this series explains how JavaScript and C # differ when programming in the Unity3d game engine. It is recommended that you first read the first and second sections to facilitate understanding of this section.

In the third section, the main explanation is how to use JavaScript and C # to make a gameobject move forward differently. Now let's take a look at a code that uses JavaScript to move a gameobject forward:

public Var gotransform:transform;

private var vel:int = 2;//how Fast The game object is being moved

function Awake ()

{

Get this gameobject ' s Transform

Gotransform = this. Getcomponent (Transform);

}

Update is called once per frame

function Update ()

{

Moves the containing Gameobject forward

Gotransform.position.z = gotransform.position.z + vel;

}

The goal of this script is to have the z-axis coordinates of the gotransform increased in each update cycle to control the gotransform moving forward, now let's see what it would be like to write code in C #:

Using Unityengine;

Using System.Collections;

public class Pawnmover:monobehaviour

{

Public Transform Gotransform;

private int vel = 2;//how Fast The game object is being moved

void Awake ()

{

Get this gameobject ' s Transform

Gotransform = this. Getcomponent<transform> ();

}

Update is called once per frame

void Update ()

{

Returns a CS1612 error

Gotransform.position.z=gotransform.position.z + vel;//<=returns a CS1612 error

The right-to-do it when using C #

Gotransform.translate (Vector3.forward * vel);//moves the containing gameobject forward

}

}

As we can see here, in C #, it is not possible to change the z-coordinate values of gotransform directly as in JavaScript scripts, which produces cs1612error because we are going to change a value instead of referring to that value. To avoid this error, when scripting in C #, we use methods to move gameobejct, such as translate (), Rotate (), Rotatearound (), and so on. These methods are all public member variables of the transform class.

=======================================================


Yielding pauses code is quite useful for game programming, and you can use it to better control the events in your game. Neither JavaScript nor C # can easily interrupt the update () method. I believe you have guessed that what we are going to talk about today is how the two languages differ in this solution. We'll give you a common example of this solution in this section. Now let's take a look at how JavaScript is yield:

private Var texts:string;

private var counter:float = 0;

function Update ()

{

Call the function this waits three seconds to execute

Waitthreeseconds ();

}

This function waits three seconds before executing

function Waitthreeseconds ()

{

Waits three seconds

Yield Waitforseconds (3);

Converts the counter to a String and stores it value in texts

Texts = "Three seconds have passed, now I ' m counting ..." +counter. ToString ();

Add one to the counter

++counter;

}

function Ongui ()

{

The next line displays the first line of text

Gui. Label (New Rect (20,20,250,20), "I'll start counting in 3 seconds.");

Displays the counter

Gui. Label (New Rect (20,40,500,20), texts);

}

This code outputs two text on the screen, the first line is rendered shortly after the start, the second row only appears after 3 seconds of pause, and the yield code executes only once, The update () loop is then executed normally (that is, it will not wait three seconds to execute the Waitthreeseconds ()). One thing to note is that we know that using the Yield,update () method within a function can not be paused.

Now look at the C # code:

Using Unityengine;

Using System.Collections;

public class Yield:monobehaviour

{

private string texts;

Private float counter = 0;

void Update ()

{

Doesn ' t generate an error but doesn ' t work either.

Waitthreeseconds ();//<=does nothing

Start the coroutine named Waitthreeseconds

Startcoroutine ("Waitthreeseconds");//<=right

}

Waits three seconds before executing

IEnumerator Waitthreeseconds ()

{

Waits three seconds

Yield return new Waitforseconds (3);

Converts the counter to a String and stores it value in texts

Texts = "Three seconds have passed, now I ' m counting ..." +counter. ToString ();

Add one to the counter

++counter;

}

void Ongui ()

{

The next line displays the first line of text

Gui. Label (New Rect (20,20,250,20), "I'll start counting in 3 seconds.");

Displays the counter

Gui. Label (New Rect (20,40,500,20), texts);

}

}

The main difference is that we can't put yield in a function in C # and need to use the IEnumerator interface, which is only because C # is so designed (more information about the IEnumerator interface can be found in/HTTP www.devarticles.com/c/a/C-Sharp/Interface-IEnumerable-and-IEnumerator-in-C-sharp/2/ Found here) we cannot invoke Waitthreeseconds () like a normal function, even if that does not have any reaction. So our solution is to invoke Waitthreeseconds () in the same way we call collaboration. (e.g. 14 rows)

Another difference is that in 21 rows, we'll replace the yield waitforseconds (3) code with yield return new Waitforseconds (3) because we need a return value with the IEnumerator interface.

====================================================


Let's take a look at the basics: What is ray projection? As the name implies, is to use the program to simulate a real life is played a ray ("Ray", Translator: O (∩_∩) o haha ~ my name). Useful in game programming, the Raycast class can return the distance from the source point to the ray colliding with an object (sometimes used to get the name of the colliding object). Unity3d does not have a separate raycast class, it is a class that is functionally dispersed by physics, Raycasthit, and Ray.

Let me give you an example of using JavaScript to project rays:

Creates a Ray object

private Var Ray:ray;

Creates a raycasthit, to query informarion on the objects that is colliding with the Ray

private var hit:raycasthit = new Raycasthit ();

Get This gameobject ' s transform

private Var Capstrans:transform;

function Awake ()

{

Get this Transform

Capstrans = this. Getcomponent (Transform);

}

Update is called once per frame

function Update ()

{

Recreate the ray every frame

Ray = new Ray (capstrans.position, Vector3.left);

Casts a ray to see if something has hit it

if (Physics.raycast (ray.origin,ray.direction, hit, ten))//cast the ray units in distance

{

Collision have happened, print the distance and name of the object into the console

Debug.Log (Hit.collider.name);

Debug.Log (hit.distance);

}

Else

{

The ray isn ' t colliding with anything

Debug.Log ("None")

}

}

Let's see how it works:

First, we need to create a Ray object, and each frame is recreated once (for example, lines 2nd and 20), which has properties such as the direction and source of the ray projection.

Then we need a raycasthit class object that gets the distance and some other details of the ray's collision with other gameobject.

Next, we need to call the Raycast () static method from the physics class (for example, 23 rows), this method will actually project a ray, record the source point of the Ray, the direction of the projection, the Raycasthit object and distance these parameters, The distance and collision results are then passed to the Raycasthit object.

It may sound a little messy at first blush, but it's a bit more time to try it out (see http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html for more information), and then take a look at the C # code:

Using Unityengine;

Using System.Collections;

public class Raycast:monobehaviour

{

Creates a Ray object

Private Ray Ray;

Creates a raycasthit, to query informarion on the objects that is colliding with the Ray

Private Raycasthit hit = new Raycasthit ();

Get This gameobject ' s transform

Private Transform Capstrans;

void Awake ()

{

Get this Transform

Capstrans = this. Getcomponent<transform> ();

}

Update is called once per frame

void Update ()

{

Recreate the ray every frame

Ray = new Ray (capstrans.position, Vector3.left);

Casts a ray to see if something has hit it

if (Physics.raycast (Ray.origin, ray.direction, out hit, ten))//cast the ray units in distance

{

Collision have happened, print the distance and name of the object into the console

Debug.Log (Hit.collider.name);

Debug.Log (hit.distance);

}

Else

{

The ray isn ' t colliding with anything

Debug.Log ("None")

}

}

}

When projecting rays, the only difference between the two programming languages is on the 28th line of code. Now let's see how we can pass the hit object out of the keyword. Because the Raycast () method in C # requires a reference to the Raycasthit parameter, this happens to be an out keyword thing to do. So we use a reference to pass a raycast () instead of passing the object (as we did in JavaScript). (For more information, refer to Http://msdn.microsoft.com/en-us/library/t3c3bfhx (v=vs.80). aspx).

Comparison of JavaScript and C # in Unity3d

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.