Script overview
This is a simple overview of how the Unity internal script works.
The Unity internal script is made up of additional custom script objects to the game object. Non-gay functions within a script object are invoked by a particular event. The most commonly used columns are listed below:
Update: This function is called before rendering a frame, where most of the game code is executed in addition to physical code.
Fixedupdate: This function is called once in each physical time step, which is where the physical game is handled.
Code outside of any function:
Code outside any function runs when the object is loaded, which can be used to initialize the script state.
Note: This part of the document assumes that you are using JavaScript to write information about how to write scripts using C # and Boo in C #.
You can also define event handlers whose names start with on, (such as Oncollisionenter), and refer to the Monobehaviour documentation for a list of the complete predefined events.
Common operations
Most game objects are manipulated by transform or rigidbody of game objects, which can be accessed through transform and rigidbody, respectively, so if you want to rotate 5 degrees around the y-axis, you can write as follows:
function Update () {
Transform. Rotate (0,5,0);
}
If you want to move an object forward, you should write as follows:
function Update () {
Transform. Translate (0,0,2);
}
Tracking time
The time class contains a very important class variable, called Deltatime, that contains the current amount from the last call to update or fixedupdate (depending on whether you are in the update function or in the Fixedupdate function).
So for the above example, modify it so that the object rotates at a constant speed without relying on the frame rate:
function Update () {
Transform. Rotate (0,5*time.deltatime,0);
}
Moving objects:
function Update () {
Transform. Translate (0, 0,2*time.deltatime);
}
If you add or subtract a value for each frame change, you should multiply it with the time.deltatime. When you multiply time.deltatime, your actual expression: I want to move this object at 10 m/s is not 10 m/frame. This is not just because your game will run independently of frames, but also because the unit of motion is easy to understand. mph
Another example, if you want to increase the range of illumination over time. The following expression changes the RADIUS in 2 units/sec.
function Update () {
Light.range + = 2.0 * time.deltatime;
}
When dealing with a rigidbody through force, you usually do not have to use time.deltatime, because the engine has taken this into account for you.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/