Unity3d Script Programming

Source: Internet
Author: User

Tribute to the original http://blog.csdn.net/kfqcome/article/details/10159057

An overview of creating and using scripts 1

The behavior of Gameobject is controlled by the components attached to it, and the script is essentially a component.

Create a script in unity with the following default content:

[CSharp]View Plaincopy
  1. Using Unityengine;
  2. Using System.Collections;
  3. Public class Mainplayer:monobehaviour {
  4. Use this for initialization
  5. void Start () {
  6. }
  7. Update is called once per frame
  8. void Update () {
  9. }
  10. }




A script establishes a connection with Unity's internal working mechanism by implementing a class derived from "Monobehaviour". The class of the newly created component type can be used as a blueprint, and the class is attached to the game object as a new type of component. Each time a script component is attached to a game object, an instance of the object defined by that blueprint is created. The script file that you create must have the same name as the class name inside it so that you can attach it to the game object.

The main thing to notice is that the two functions defined in the class. The update function handles frame update related actions for game objects. This may include movement, triggering actions, and feedback on user input, and basically anything that needs to be handled during the course of the game can be handled here. The start function is called by unity before the game starts (for example, before the update is first called), and thus is an ideal place to initialize.

It may be doubtful why the initialization is not placed in the constructor of the class, because the object's construction is handled by the editor and does not occur as expected at the beginning of the game. If you define a constructor for a script component, it interferes with the normal operation of unity and causes some problems.

After the script is created, it is inactive and the code is activated only after attaching one of its instances to a game object. At the same time, there can be only one type of component for a game object, that is, no more than one script component that can be attached to the game object.

2 variables

Refers to the member variables of the class, but in unity here the member variable is set to the public, after attaching it to the game object, you can see in the game object's monitoring panel in the script component that bar in the field of the public variable, that is, you can directly in the editor of the public variable assignment, You can also see its value in the panel in the debug state.

When unity displays a member variable of a class in the editor, when it encounters (not the first letter) capital letter in the class name, a space is added to the letter, such as defining a public member variable named "TestVar" in the class, and the variable named "Test Var" displayed in the editor. A space is added to the middle, but this is just a way for unity to display the variable, and the name "TestVar" should still be used to actually access the variable in the code.

3 Event functions

The script in unity is not like a traditional program, which runs continuously in a loop until the task is completed and then quits, but unity gives control to a script intermittently by invoking a function defined within the script. Once a function completes execution, control is returned to unity. These functions are known as event functions, because they are called by unity to respond to events that occur during gameplay. All the events supported by unity are defined in the Monobehaviour, and you can see a series of events in the reference document for that class. Here are a few of the most common and important events.

<1> General Update event (Regular update events)

A game is more like an animation that generates animated frames online. A key idea in game programming is to change the position, state, and behavior of a game object before each frame is rendered. The update function is the main place in unity where such code is placed, before each frame is rendered, and also before the animation is evaluated.

Update Event function

void Update () {
float distance = speed * Time.deltatime * Input.getaxis ("horizontal");
Transform. Translate (Vector3.right * speed);
}

The object engine is also updated every other discrete time period in a similar way to frame rendering. Another function called Fixedupdate is called before each physical update. Because physical updates and frame updates do not use the same frequency update, if you put the above code in the Fixedupdate function instead of the update function, you can get more accurate results (that is, Fixedupdate will run at a more stable frame rate than the update).

void Fixedupdate () {
Vector3 force = transform.forward * Driveforce * Input.getaxis ("Vertical");
Rigidbody. Addforce (force);
}

At the same time, after the update and fixedupdate calls of all objects in the scene, and after all animation calculations, there may still be some additional changes that need to be made. An example is when a camera needs to monitor a target object, the orientation of the camera must be adjusted after the target object has moved. Another example is when you need to use scripting code to override the animation effect (for example, to make the head of a character look at the target object in the scene). The Lateupdate function can be used for these occasions.

<2> Initializing Events

Calling initialization code before any update function in the game is often used, and the initialization function start is called before the object's first frame is updated or the physical update is made. The awake function is called on every object in the scene when the scene is loaded, and all the awake functions are called before the first start function (many of them have a number of start functions). This means that the code in the start function can also use the initialized data that occurs in the awake phase.

<3> GUI Events

Unity has a system for rendering GUI controls that are on top of the scene and respond to mouse events. This code is somewhat different from regular frame updates, so it needs to be placed in the Ongui function and periodically called.

void Ongui () {
Gui. Label (Labelrect, "Game over");
}

These messages can also be detected when a mouse clicks on a game object in the scene. This can be used to adjust the weapon or display the character information currently under the mouse. A series of ONMOUSEXXX event functions can be used to interact with the user's mouse behavior.

<4> Physical Events

The physical engine reports the occurrence of a collision event with another object by invoking an event function on the object. The Oncollisionenter, Oncollisionstay, and oncollisionexit functions are called when they are just touching, persisting, and leaving (broken). The corresponding oncollisionenter, Oncollisionstay, and Oncollisionexit are called when the collider is configured as a trigger. If more than one contact is detected during a physical update, these functions may be called more than once (that is, one round after the call).

Two control game objects

In unity, you can modify the component properties of an object in the monitor panel, but more often, you need to use a script to do so.

1 Accessing components

The most common scenario is to use a script to access another component attached to the same game object (the current script is a component, and the other component is another component). As mentioned in the introduction, a component is essentially an instance of a class, so the first thing you need to do is get a reference to the component instance you want to manipulate. This is done through the getcomponent function. Typically, you might want to assign a component to a variable, as shown in the following code

void Start () {
Rigidbody RB = getcomponent<rigidbody> ();
}

Once a reference to a component instance is obtained, it is possible to perform the desired action on its properties, as well as to invoke some function functions on top of it.

If you want to access another script file, you can also use getcomponent, just use the script's class masterpiece as the function's component type parameter (because the script is also a component).

If you want to get a component that is not added to the current game object, the Getcomponent function returns NULL, and if you try to change any value on a null object, a null reference error will occur.

Because some component types are used frequently, unity provides some built-in variables to access them, for example, the following code can be used

void Start () {
Transform.position = Vector3.zero;
}

Instead of using getcomponent to get the transform component, all of the built-in component variables are listed in the Monobehaviour class reference manual .

2 Accessing other objects

While game objects are sometimes handled individually, it is common to use code to track other objects. For example, a catch-up foe may need to know the player's location, Unity offers a number of different ways to get other objects, each suitable for different occasions.

<1> linking objects to variables

The most straightforward approach is to add a game object to the public member variable of the script, and drag the game object that needs to be accessed directly to the public member variable of the corresponding script component in the editor, and unity automatically maps the same component type in the game object that is added to the variable according to the type of the variable.

For example, by dragging a game object to a transform member variable, the transform component of the game object and the variable are automatically mapped.

Linking objects and variables directly is the most useful way to handle objects that need to have permanent links. You can also use an array variable to link to several objects of the same type, but the link must be done in the Unity editor and not at run time. You typically use the following two methods to locate an object at run time.

<2> Finding sub-objects

Sometimes, a game scene may use many objects of the same type, such as enemies, Road points (waypoints), and obstructions. These objects need to be monitored and responded to by a particular script in the game. Using variables to link these objects at this time is too cumbersome and difficult to manipulate. In this case, it is usually better to add a series of objects underneath a parent object that can be obtained by using the Transfrom component of the parent object.

[CSharp]View Plaincopy
    1. Public class Waypointmanager:monobehaviour {
    2. Public Transform waypoints;
    3. void Start () {
    4. waypoints = new Transform[transform.childcount];
    5. int i = 0;
    6. For (Transform T in Transform) {
    7. waypoints[i++] = t;
    8. }
    9. }
    10. }




You can also use Tranfrom.find to find a specific sub-object. Object lookup operations are performed using transform because each game object has a transfrom component.

<3> accessing objects by name or tag

As long as there is some information, it is possible to navigate to the game object anywhere in the hierarchy scene. A single object can be found through the Gameobject.find function. As follows:

Gameobject player;

void Start () {
Player = Gameobject.find ("Mainherocharacter");
}

An object or a series of objects can also be positioned by using the Gameobject.findwithtag and Gameobject.findobjectswidthtag functions, respectively.

<4> finding objects of a specific type

StaticObjectfindobjectoftype (type type)

Returns the loaded object of the first activity in a specified type Object

It is important to note that this function is very slow (possibly due to traversing the entire scene), it is not recommended to use this function for every frame, and in most cases a single-piece mode can be used

For example

Camera cam = Findobjectoftype (typeof (Camera)) as Camera;

Because the type returned by this function is object, you need to use as for the cast.

Static object[] Findobjectsoftype (type type);

Returns the list of loaded active objects of the specified type, which is also slow

Hingejoint [] hinges = Findobjectsoftype (typeof (hingejoint)) as hingejoint[];



Three creating and destroying objects

Creating and destroying objects at run time is often the case. In unity, you can use the instantiate function to make a copy of an existing object to create a new game object.

Public Gameobject Enemy;

void Start () {
for (int i = 0; i < 5; i++) {
Instantiate (enemy);
}
}

It is important to note that the objects used for copying do not necessarily need to be placed in the scene. It is more common to drag a preset (Prefab) onto the corresponding public member variable of the script and instantiate the member variable directly.

There is also a destroy function that destroys an object after the frame update function is complete or after a set delay time.

void Oncollisionenter (otherobj:collision) {
if (Otherobj = = "Missile") {
Destroy (gameobject,.5f);
}
}

Note that the Destroy function can destroy individual components without affecting the game object itself, a common error is

Destroy (this);

This code only effects the script component, and does not destroy the object that the script attaches to.

Four-process (coroutines)

When a function is called, it runs to the end position before returning.

As you can see from the previous knowledge, almost all functions are called once by unity at the time of the frame update and then called again after the next frame, when writing the code of the loop body class in the function to achieve an animated effect may fail. As follows

[CSharp]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. void Fade () {
    2. for (float f = 1f; f <= 0; F-= 0.1f) {
    3. Color C = renderer.material.color;
    4. C.alpha = f;
    5. Renderer.material.color = C;
    6. }
    7. }



This is the effect of trying to create a transparent gradient, but since the fade function is fully executed in a frame update time slice, the gradient effect is not achieved. To achieve this effect, you can do this in the frame update function. However, it would be more convenient to use coroutine for such situations.

A coroutine is like a function that can pause execution and return control to unity, but can continue at the next frame where it stopped. In C #, this declares a coroutine:

[CSharp]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. IEnumerator Fade () {
    2. for (float f = 1f; f <= 0; F-= 0.1f) {
    3. Color C = renderer.material.color;
    4. C.alpha = f;
    5. Renderer.material.color = C;
    6. Yield return;
    7. }
    8. }



Essentially it is a function that returns a type of IEnumerator, and adds the yield return code to the function body. Yield return this line is where execution pauses and resumes execution at the next frame. To start coroutine, you need to use the Startcorutine function.

[CSharp]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. void Update () {
    2. if (Input.getkeydown ("F")) {
    3. Startcoroutine ("Fade");
    4. }
    5. }



By default, a coroutine is resumed on the next frame after it pauses, but you can also use Waitfroseconds to introduce a delay.

[CSharp]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. IEnumerator Fade () {
    2. for (float f = 1f; f <= 0; F-= 0.1f) {
    3. Color C = renderer.material.color;
    4. C.alpha = f;
    5. Renderer.material.color = C;
    6. Yield return new Waitforseconds (. 1f);
    7. }
    8. }



This can be used to produce an effect that changes over time and is also an effective way to optimize. Many of the characters in the game need to be executed periodically, and the most common practice is to include them in the update function. However, the update function is typically called multiple times per second. When a task does not need to be called so frequently, it can be placed in a coroutine for a certain amount of time, instead of being called every frame. One such example is used to prompt the player if there is an enemy approaching in the game, the code is as follows

[CSharp]View Plaincopy
  1. function Proximitycheck () {
  2. for (int i = 0; i < enemies. Length; i++) {
  3. if (Vector3.distance (transform.position, enemies[i].transform.position) < dangerdistance) {
  4. return true;
  5. }
  6. }
  7. return false;
  8. }
  9. IEnumerator Docheck () {
  10. for (;;) {
  11. Proximitycheck;
  12. Yield return new Waitforseconds (. 1f);
  13. }
  14. }



When there are many enemies, using coroutine0.1 seconds to perform a close inspection can reduce the amount of computation.

Unity3d Script Programming

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.