C # Developing the game object's behavior logic method of Unity game tutorial The behavior logic of game object--method
method, the reader in the 1th chapter of the new script has been seen, and in the 2nd chapter on the overall introduction of the script is also introduced, then the last chapter, although the main content is variable, but at the end of the chapter in order to show the game effect, also used it. Now it seems that the method is really ubiquitous and indispensable. It can even affect the behavior logic of the game Object! So this chapter has finally come to the point where it has to be introduced.
Behavior logic for Unity game objects
In the game scene, some of the game objects are still, for example, trees, mountains, stones and so on. Other game objects are sports, and they all have their own behavioral logic. For example, a computer-controlled game object may travel according to a predetermined line, and if it encounters a player-controlled game object on the way, it will also initiate an attack. As shown in 4-1, the behavioral logic is embodied in the game "alloy warhead". Whether marching or attacking, this belongs to the behavior logic of the game object, and the decision of this behavior logic is the method in the script.
Fig. 4-1 The behavior logic of each game object in "alloy warhead"
Methods in the Unity script
The first two chapters have done two game examples, and the cube object will be rotated along the front edge, and the cube in the second example will move, rotate, and scale when the player clicks the specified button. In both of these games, the cube shows specific behavioral logic, and the method that determines the logic of the behavior. 4-2 shows the script method in the first game example.
Figure 4-2 How the game object's behavior logic is determined in the script
At the end of the previous chapter, the reader is introduced to the sentence, then look at the method in the script, its external representation is composed of one or more statements. Typically, variables declared in a script are used to store data, and the methods in the script do some processing on the data and then apply that data to the control of the game object's behavior logic. For example, the example shown in the previous chapter, which adjusts the value of the property in the Inspector view, affects the scale size of the cube object, which is 4-3.
Figure 4-3 the method in the script that applies the data in the attribute to the control of the game object's behavior logic
Using scripting Methods in unity
As explained earlier in this chapter, the reader may have realized how important the method is, so that the game example presented in the previous two chapters must be assisted by the method to achieve the final result. The method is so magical that the reader must now be interested to understand, then this section will gradually uncover the mystery of the method.
Methods and variables in unity
There are many similarities between methods and variables. For example, a variable is not equivalent to a variable name, as is the method name. The specific instructions are as follows:
- The Q method is also a specific storage space, but the method is not stored in the data, but the code statement;
- The Q method name also needs to follow the C # naming convention, where the name must consist of letters, numbers, and underscores, and the number cannot be the first letter of the name, otherwise it is a grammatical error;
- Q in order to distinguish the method name from the variable name, the reader may consider adhering to the Convention that the first letter of the variable name is lowercase and the first letter of the method name is capitalized. Since this is an agreement, the reader can of course not abide by, and will not make grammatical mistakes;
- Q is like a variable name, the method name should also take a meaningful. For example, since the method can control the logical behavior of the game object, it is possible to consider a method name similar to cubewalking for controlling the movement of the Cube;
- Q can also be modified with public and private, except that the method uses any adornments, and the results are not reflected in the Inspector view, but only in the use of the method. Even the public-modified method can be used by other scripts, and the private adornment is the opposite. If you omit the adornment of a method, unity will assume that the way is modified by private.
Defining Methods in Unity
Just like declaring a variable before using a variable, you need to define the method before you use it. It's like telling unity that there is a way that this method can control the game object to make a specific behavior. The method is defined in the following form:
- Return value type method name ()
- {
- The statements in the method
- }
- The pair of parentheses "()" after the Q method name is essential;
- Q The statement enclosed by braces "{}" can be thought of as data stored in a method;
- Q When declaring variables, some readers notice that it ends with a semicolon ";" At the end, but for the definition of the method, the "}" in the curly braces is the end tag, and the reader does not need to "superfluous";
- The Q method can "return a specific type of data";
For example, when you write a game in the previous chapter, one of the methods used in the script is as follows:
- void Update ()
- {
- Transform. Translate (New Vector3 (xposition,0,0), Space.world);
- Transform. Rotate (Vector3.up*yrotation,space.world);
- }
For this approach, unity will understand this:
- Q This method is named Update ();
- A total of two statements in the Q method;
- The data type returned by the Q method is void. This type indicates that the method does not return any values. Therefore, rather than void means a type, it is rather a sign, that is, a flag that does not return any type of data;
- Q omits the modification of the method, so unity will consider it to be private, so the other scripts cannot use this method;
Calling Methods in Unity
After the method has been defined, it can be used directly. The use of the method in the script has a special term, that is, "call method." The way you invoke a method in a script is simple, just use the method name, but don't forget to take the following pair of parentheses "()". As follows:
- Definition part of a method
- ...//omitted
- Calling methods
- Addtwonumber ();
Examples of methods used in unity
The theoretical part has been written a lot, and readers should be impressed with the concept of the method. Now it's on the strike. An example is used to illustrate the definition and invocation of a method. The following are the steps to implement the example:
(1) In Project view, create a new script file named MyScript, open the script file and add the following code:
- Using Unityengine;
- Using System.Collections;
- 03
- public class Myscript:monobehaviour
- 05 {
- private int number1 = 15;
- The private int number2 = 59;
- Ongui void ()
- 09 {
- Ten Guilayout.label ("number1 =" + Number1);
- Guilayout.label ("number2 =" + number2);
- Guilayout.label ("Number1 + number2 =" + Addtwonumber ()); // How to use
- 13}
- + int Addtwonumber ()// fixed to method
- {
- return number1 + number2;
- + }
- 18}
Readers must be familiar with the 06 or 07 lines of code for this script. The code here completes the declaration and initialization of the variable. Variables are highlighted in the previous chapter, and this chapter focuses on the definition of the 14~17 line method and the invocation portion of the 12-line method.
- Q from the definition of a method, the method named Addtwonumber () returns data of type int, with only one line in the method, and the meaning of the statement is to calculate the number of two integers.
- Q from the method call, the way to use the method is very simple, directly write Addtwonumber () can be.
(2) Add the script MyScript to the main camera object, except that no other game objects are needed in the game scene. Running the game directly, there will be 3 lines of text information in the upper left corner of the game view, as shown in 4-4.
Figure 4-4 Text information in the upper-left corner of the game view
(3) This is just an example of an example that allows the reader to familiarize themselves with the method definition and invocation. So there is no way to control the game object's behavior logic, as for the method of the game example, will be given after the end of this chapter after the explanation.
Unity built-in methods
The new script file in unity will automatically add some code, as shown in 4-5. After the reader has learned the method, there is no sense that the automatically added code, Start () and update () The writing form is much like the method. Yes, they are the methods. But they are the unity built-in method that they are called by the game program.
Figure 4-5 the code that unity automatically adds in the script
Because these two methods are common in scripts, unity adds them directly to the new script. So, the reader may ask, how will these two methods be used for the game object? Annotations are used in the code (double slash "//" and later in the comments) to illustrate these two methods simply: The former is called at initialization, which is called at each frame of the game's running process. If the reader is not satisfied with the explanation on the comment, consider reviewing the help documentation for unity. In the 1th chapter, the author introduces how to open and retrieve the Help document, and if you forget, you can review the following.
For an example, find the instructions for using the start () method. Enter Monobehaviour.start in the search box in the Help document to begin the search. In general, you will find a lot of results, select the desired results, open it. The entire procedure is shown in 4-6.
In the Help documentation, you will first briefly describe the functionality and use of this method, and at the end, give an example of how this method is used.
Tips: Unity's scripts can be written in three languages, which are C #, JavaScript, and Boo, so the help document gives examples of using these 3 languages separately. Because the language used in this book is C #, it is recommended that readers look at examples written in the C # language.
Figure 4-6 Using the help document provided by unity to see instructions for using the start () method
Here is an example of how unity built-in methods start () and update () are used. The procedure for the example is as follows:
(1 Open the script MyScript and add the following code to it:
- Using Unityengine;
- Using System.Collections;
- 03
- public class Myscript:monobehaviour
- 05 {
- private int framecount = 0;
- void Start ()
- {
- Debug.Log ("This is the output information in Start ()");
- Ten }
- void Update ()
- {
- framecount++;
- if (Framecount = = 100)
- 15 {
- Debug.Log ("This is the output information in update ()");
- Framecount = 0;
- 18}
- + }
- 20}
The newly added code adds a single statement (09 rows) and multiple statements (13~18 rows) to start () and update (), each of which outputs a line of text information in Unity's console view. The reader can learn from the output information about the invocation of Start () and update ().
(2 Run the game, the focus of this observation is not the game view, but the console view, the output text information, 4-7 is shown.
Figure 4-7 The text information output of the console view
With the help document provided by unity, the reader should be aware that the method start () is called when the game object is initialized and is called before update (). Therefore, the first output in the console view is the text information in the start () method, and then the update () method is called, so the text information in the update () method is then output. Also, because the update () method is called at each frame, the text information in the update () method continues to be output during the game's run.
Tip: If you let the update () method output information for each frame, the console view will soon be "brushed". To prevent this from happening, the script code simply lets the update () method output text information once every 100 frames, but the update () method is still called at each frame.
Parameters for methods in unity
The method that appears in the script, whether it is at the time of definition, or when used, followed by a pair of parentheses "()", does it make sense? It looks like the most important way to get a quick identification. Since the syntax of C # should be written in this way, there must be some truth to it. If it is a strategic point of rise, even the author is not very clear, but the author knows that the parentheses can be added "parameters."
The role of parameters in unity
To explain the function of the parameter, it must start from the method. Method can handle the data in a variable, which in turn affects the behavior logic of the game object, which is highlighted earlier in this chapter. However, in cases where there are no arguments in the parentheses of the method in the previous script, the method always handles the data in a particular variable. For example, the following is the method defined in the previous example:
- int Addtwonumber ()
- {
- return number1 + number2;
- }
There are no parameters in the parentheses of this method, and the data it processes is always the data in the variables number1 and number2. Since this is only a method for summing, it is not necessary to specify that it only calculates the data in the variables number1 and number2. If the data of other variables are also required, then a method can be defined. This kind of problem can be solved well by introducing parameters into the method.
For the actual meaning of the game
The developer defines a way to control the logical behavior of a game object. If other objects also need to make similar behavior, there is no need to define a method. For example, the following game example does.
(1) Add cube, cylinder and directional light to the game scene, these 3 game objects. The first two are the game objects that control the behavior logic as a scripting method, and the last game object is responsible for the lighting of the game scene. Set their respective positions reasonably and get the scene and game views, as shown in 4-8.
Figure 4-8 in scene and game view, view the relative position of each object, and the effect of the game view
(2) In Project view, create a new script file named MyScript, open the script and add the following code:
- Using Unityengine;
- Using System.Collections;
- 03
- public class Myscript:monobehaviour
- 05 {
- Public Gameobject Mycube;
- Public Gameobject Mycylinder;
- Ongui void ()
- 09 {
- 10//When the left mouse button is pressed
- if (Input.getmousebutton (0))
- Rotateobject (mycube);
- 13//When the right mouse button is pressed
- if (Input.getmousebutton (1))
- Rotateobject (mycylinder);
- 16}
- 17//Change the way the game object faces
- rotateobject void (gameobject myObject)
- {
- myObject.transform.Rotate (vector3.right*100,space.world);
- + }
- 22}
- Q The 18~21 line of the script code is the defined part of the parameter method. From the code point of view, the passed parameter is a game object, and the statement in the method is to change the object orientation of the game objects by modifying the Rotation property under the transform component of the game object;
- Q Script code of 12, 15 lines, called two times Method Rotateobject (), successively passed parameters are not the same;
(3) Assign the script MyScript to the main camera object, and in the latter's Inspector view, set the My cube and my cylinder properties in the My script component to the cube and cylinder objects in the game scene, The property is set by dragging the cube and cylinder objects in the hierarchy view directly into the corresponding property box, as shown in 4-9.
Figure 4-9 Setting properties under the My Script component
(4) Run the game, in Game view, always press the left mouse button, the reader will see the cube object in situ scrolling. If you keep pressing the right mouse button, then scrolling in place becomes a cylinder. If you hold down the left and right mouse buttons at the same time, the cube and cylinder will scroll at the same time, as shown in 4-10.
Figure 4-10 The game effect display diagram
(5) In the game, the method that controls the scrolling of the game object is Rotateobject (), which is a method that needs to pass in the parameter. Because of the need to pass in parameters, it can be used in the game scene, all game objects scrolling behavior logic control. Instead of just controlling the behavior logic of an object individually.
This article is selected from: C # Game Development Quick Start University PA Internal information, reproduced please indicate the source, respect the technology respect the IT person!
C # Developing the behavior logic method of game objects in Unity game tutorial