[Unity3d] basic use and introduction of Javascript in unity3d

Source: Internet
Author: User
Tags translate function uppercase letter
Scripts are essential in unity. Because it will define the various behaviors and rules of your game.

This tutorial will introduce the basic usage of JavaScript.
1. Objectives

In unity, scripts are used to define users' behaviors or rules in the game. The recommended programming language for unity is JavaScript, and C # Or Boo is also supported.


2. Prerequisites

This tutorial focuses on the basics of Unity scripts, provided that you are familiar with the unity interface.


3. Naming rules
Before you begin, let's talk about some unity specifications.
Variable-the first character is a lowercase letter. Variables are used to store any information in the game status.
Function-the first write is an uppercase letter. A function is a code block that can be repeatedly called as needed.
Class-the first write is an uppercase letter. It can be considered a function library.

When reading the example, pay attention to the first letter, which will help you better understand the relationship between objects.


4. user input
The first example is to implement a simple movement in the scene.
1) set the scenario:

-Start unity. Create a plane to move. Gameobject-> createother-> plane. In the Inspector panel, set position to "0, 0 ". If no inspector panel exists on the current page, choose Window> layouts> 2by 3. We recommend that you familiarize yourself with various la s for development purposes.

-Create a cube. Gameobject-> createother-> cube. In the Inspector panel, set position to "0, 1, 0 ".

-We all know that in the real world, object imaging relies on light reflection, so we also need light here. Choose gameobject> createother> pointlight. In the Inspector panel, set the coordinates to ", 0 ".

-Save the current scenario. The shortcut key is Ctrl + S.

2) create a script.
We intend to move the user's line of sight, which needs to be achieved by controlling the location of the master camera.
We need to write a script and then combine the script with the camera.

-Create an empty script. Assets-> Create-> JavaScript and name it "move ". Rename the shortcut key to F2.

-Double-click to open the script move. The Update () function is included by default. Add our code to this function and it will be executed once at each frame.
We need to use transform to change the camera position and use the translate function. It has three parameters: X, Y, and Z. Add the following code:

function Update(){    transform.Translate(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));}

The input. getaxis () function returns a value from-1 to 1. For example, the left half axis on the horizontal axis is-1 to 0, and the right half axis is 0 to 1.
If necessary, you can use Edit-> projectsettings-> input to redefine the key ing.

3) connection script
After writing the script, how can I make it work? We need to assign the script to the object.

-Click the object to which you want to apply the script. This is the camera for us. Select hierarchy from the hierarchy panel.

-Select components-> scripts-> move from the menu, so that we can see the move component added to the camera from the Inspector panel. (You can also drag the script to an object with the mouse)
Click "run". We can press the buttons on the left and right to control the camera movement.

Pay attention to a question about deltatime. The code in the update () function is executed by frame.
If we need to move an object in seconds, we need to multiply the return value of the Input. getaxis () function by time. deltatime:

var speed = 5;function Update(){var x = Input.GetAxis("Horizontal")*Time.deltaTime*speed;var y = Input.GetAxis("Vertical")*Time.deltaTime*speed;transform.Translate(x, y, 0);}

In this way, press WASD to move the angle of view from top to bottom to the left.
Here, speed is an explicit variable, which can be seen in the Inspector panel. We can adjust its value at any time during use, which is very convenient.

5. Connection Variables
Unity allows you to assign scripts by dragging (drag and drop) on the interface. Quick and convenient. Here, we will involve the concept of connection variables.

-Add a spotlight to the scene. Gameobject-> createother-> spotlight. Position is "0, 5, 0", and rotation is "90, 0, 0 ".

-Create a Javascript script named "spotlight ".

We want the spotlight to be directed to the main camera. We can use the transform. lookat () function.
How to use this function? We need to create an explicit variable. Write the following code in the sporlight script:

var target : Transform;function Update(){transform.LookAt(target);}


-Assign the script to the spotlight object. Either Add the component in the menu bar or drag and drop the mouse. Then, the "target" variable appears in the Inspector panel.

-Drag and Drop the master camera object in the hierarchy panel to the target variable. If we want the spotlight to shine on other objects, we can drag and drop other objects, as long as they are of the transform type.
-Run. You can see that the spotlight is always directed to the main camera.

6. Access Components
A game object may have multiple scripts or other components. It will inevitably access functions or variables of other components. The getcomponent () function is used in unity to achieve this goal. Now we need to press the space bar to let the spotlight shine to the cube.
Let's consider this step: 1. monitor that the Space key is pressed. 2. Press the Space key and the spotlight is directed to the cube.
Because the sporlight script contains the target variable, we only need to set a new value for this variable.

-Create a script named switch and add the following code:

var switchToTarget : Transform;function Update(){if(Input.GetButtonDown("Jump"))GetComponent(SpotLight).target = switchToTarget;}

Note that the getcomponent () parameter returns a parameter to the switch script, and we can use it to access the "target" variable.
Here, getcomponent does not obtain the point light source, but the JS file named spotlight.

-Add the switch script to the spotlight object and drag and drop the cube to the switchtotarge variable in the Inspector panel.

-Run. After a space is pressed, the spotlight is directed to the cube.

 

As we mentioned above, how can we specify variables (instead of the Unity Interface) by writing code? When we press a space, we will tell the spotlight to focus on the cube. We will make an explicit variable in the spotlight script to drag and drop the cube. There are two main methods to implement the Code:
1. Use the Object Name (name)
2. Use tags of Objects)

1. Object Name
You can see the object name on the hierarchy panel. Use the gameobject. Find () function to take these names as parameters. Therefore, we can write as follows:

function Update(){if(Input.GetButtonDown("Jump")){var newTarget = GameObject.Find("Cube").transform;GetComponent(SpotLight).target = newTarget;}}

Note that no explicit variables are displayed.

2. Object Tag
An object tag is a string used to identify a component. Click the tag button on the inspector panel to view the built-in labels. You can also create your own labels. The gameobject. findwithtag () function can search for components by TAG and return a string as a parameter.

function Update(){if(Input.GetButtonDown("Jump")){var newTarget = GameObject.FindWithTag("fang").transform;GetComponent(SpotLight).target = newTarget;}}


7. Instance
We need to use the instantiate function to create (create) objects at runtime.
Let's implement how to instantiate a new object by pressing the fire button (left mouse or Ctrl) each time. Consider the following:
1. Which object is used as an example?
2. Where to instantiate it?
The best way to solve the first problem is explicit variables.
In this way, we can change our instance objects at any time through drag and drop.
As for where to instantiate, we only need to create an object at the user's current position when the fire key is pressed.
The instantiated function has three parameters: 1. the object to be created. 2. coordinates of the object. 3. the Rotation Position of the object.
The complete code is as follows:

var newObject : Transform;function Update(){    if(Input.GetButtonDown("Fire1")){        Instantiate(newObject, transform.position, transform.rotation);    }}

Remember that transform, position, transform, and rotation are the locations of objects appended to this script. Let's assume that the main camera is used. In general, the object to be instantiated is set as a preset (prefab), and we now set the Cube as a preset.
-First, let's create a preset. Assets-> Create-> Prefab. Name it cube.

-Drag and Drop the Cube from the hierarchy panel to the cube of the Project panel.

-Create a script, name it "CREATE", and add the above Code.

-Assign the script to the camera and assign the cube preset to the script variable.

-Run. Move the camera and press the fire key to see the new cube.

8. debugging
Debugging is a technique for discovering and correcting human errors in your code. Unity provides the debug class. Now let's look at the Debug. Log () function.
The log () function allows users to send messages to the unity console. The reasons for doing so may include:
1. Verify that a part of the code is reached during running.
2. report the status of the variable.
Now we use the log () function to send a message to the unity console when the user clicks the fire button.
-Open the created script and add the following code in "instantiate" code "if:

Debug.Log("Cube created");

-Run. Click the fire key, and we can see "cube created" under the unity interface ".

Another useful function is to debug private variables. This makes the variables in the Inspector panel unavailable when the debug mode is selected. To prove this, We will explicitly use a private variable as the counter of the cube instance. We add two lines of content to the script.
1. Add the private variable cubecount.
2. Add this variable after a cube instance is created.
The complete code is as follows:

var newObject : Transform;private var cubeCount = 0;function Update(){if(Input.GetButtonDown("Fire1")){Instantiate(newObject, transform.position, transform.rotation);Debug.Log("Cube created");cubeCount++;Debug.Log(cubeCount);}}

9. Common script types

// The code in this function body is executed at a fixed interval. It is usually used for powerful purposes in rigibody. For example: // apply a upwards force to the rigibody every framefunction fixedupdate () {Rigidbody. addforce (vector3.up);} // The code here will be used for initialization. Awake () {} // This function is executed before Update (), but after awake. // The difference between the start () function and the awake () function is that the START () function is executed only when the script is enabled (the check box in the Inspector panel is selected ). Start () {}// execute the code in this function when the collision script of the game object collides with another game object. Oncollisionenter () {}// the code in this function is executed when the cursor is pressed in a game object containing a GUI element or a collider. // Loads the level named "somelevel" as a response // to the user clicking on the objectfunction onmousedown () {application. loadlevel ("somelevel");} // execute the code in this function when you hover your mouse over a GUI element or collision object. For example: // fades the red component of the material to zero // while the mouse is over the meshfunction onmouseover () {Renderer. material. color. r-= 0.1 * time. deltatime ;}

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.