Unity Basic Notes (1) - Introduction to Unity Basic Operations and Basic Components

Unity Basic Operations and Components

1. Basic operation of Unity

1. Detailed explanation of Unity interface
  • Hierachy: hierarchical panel, resources in the game scene, such as UI, model;

  • Scene: Scene panel, used to manage various game objects in the game scene;

  • Game: the game scene panel, the actual player perspective;

  • Project: project panel, used to manage all resources in the project;

  • Inspector: The inspection panel can be understood as a property window to view the properties of resources in Hierachy or Project.

2. Unity game scene

Game scene concept:

​ A game can have multiple scenes. A game scene is composed of game objects. A scene is equivalent to an independent world. We can simply understand a game scene as a container of game objects.

​ When creating a project, a SampeScene scene file will be created by default, and the scene in Unity exists in the form of a file .

Game scene roaming:

​ Since the Game panel is the player's perspective, it is inconvenient to observe, so we will use the God's perspective in the Scene panel to develop the game.

​ First, you can click anywhere in the Scene panel to select the Scene panel.

Right mouse button (press and hold) : drag the mouse to rotate the viewing angle, and roam the WASD scene;

Middle mouse button : Drag the mouse to pan the angle of view ;

ALT key (press and hold) : Press and hold the right mouse button again, and drag to zoom back and forth.

2. Common components of Unity

1. Component introduction

Component concept:

For a computer in reality, the hard disk and memory stick in the computer are all components of the computer, and their common feature is replaceability .

Game components:

Unity's design idea is based on components , characters can move, characters can play animations, UI can be clicked, etc., everything is based on components.

Unity contains a large number of systems, such as the UI system. There are buttons, pictures, and drop-down boxes in the UI system. These functions are different components. The combination of these components is the UI system.

2. Unity built-in simple models and materials

Model introduction:

A model is a kind of art resource. In 3D games, three-dimensional elements such as scenes, characters, and weapons are generally models. In the learning phase, we can use Unity's built-in simple model to learn engine operation.

Add model steps: right click in the hierarchy panel --> 3DObject --> various models

Material Introduction:

The model itself is " mesh data composed of vertices ", and there is no color itself.

Materials determine the actual appearance of the model , and since we are using Unity's built-in models, materials are also a resource just like models.

3. Scene interface game object operation

toolbar:

  • Chiral tool, shortcut key Q, used to drag the scene;
  • Move tool, shortcut key W, used to move the model position;
  • Rotate tool, shortcut key E, used to rotate the model;
  • The zoom tool, the shortcut key R, is used to zoom in and out of the model;
  • Move & scale tool, shortcut key Y, can move and rotate the model at the same time.

All of the above are changing the values ​​in the Transform component of the game object.

Constraint and adsorption :

  • Change constraints : Press and hold Ctrl when moving, zooming, and rotating to constrain the moving distance, zooming degree, rotating degree, etc. The specific degree of constraint can be set in Edit --> Grid And Snap.
  • Model adsorption : press V after selecting the model , select the adsorption position and drag it to the position to be adsorbed.

Copy Model: Ctrl + c, Paste Model: Ctrl + v, Quick Copy: Ctrl + D, Quick Position: F.

4. Custom components

Why custom components?

​ The components provided in Unity are all single functions. There is no complex business logic in itself. For example, the Transform component can indeed shift the character, but when to shift is up to us to decide.

​ In general, most of the components we write are related to game logic, such as player control scripts.

Create components:

​ The design idea of ​​Unity is based on components . All our code is essentially a component. For example, if we write a function to allow the character to move, then this C# file is also a component, which can be mounted on the game object. After mounting, it can be take effect.

​Create component steps: Right-click in the project panel -> Create -> C# script, drag the script to the game object.

Component Features:

​ The scripts we create in Unity do not necessarily have to be components, so how do we determine that a script is a component?

  1. Classes that inherit MonoBehaviour are all components;
  2. Creating scripts in Unity inherits MonoBehaviour by default;
  3. Only components can be mounted on game objects .

Component learning methods:

Mainly learn from two aspects

  1. Inspector panel, components generally have some properties that can be set in the Inspector panel, then what we need to study is the impact of the settings of these properties on game objects;
  2. C# scripts, some properties in the Inspector panel, we need to use scripts to control their changes due to functional requirements.

5. Transform component

Transform component introduction:

The three main values ​​​​of the Transform component

  • Position: position
  • Rotation: rotation
  • Scale: scaling

Transform actually also contains the level information of the game object in the level panel, which will be used in the code later.

transform.positionIndicates the current position ;

transform.rotationIndicates the current rotation ;

transform.localScaleIndicates the current zoom .

How to modify the value in transform: transform.position = new Vector3(1, 1, 1);

Common properties and methods of the Transform component:

Attributes:

  1. childCount : the number of child objects;
  2. parent : the Transform component of the parent object;
  3. root : the highest level parent object;
  4. position, eulerAngles (represents the rotation modification value, rotation cannot be used directly), localScale.

method:

  1. Find (string) : Find sub-objects;
  2. Translate (Vector3) : move towards a coordinate;
  3. Rotate (Vector3) : rotate an angle;
  4. LookAt (Transform) : Look at the target.

The particularity of the Transform component:

​ In custom components, we can directly use the variable transform to access the Transform component on the current game object .

6. GameObject

What are GameObjects?

​ GameObject is the game object or game object, and all the GameObjects can be selected in the hierarchy panel.

​ At the same time, GameObject is also a type in the code, which represents the game object. In C#, you can set the value of this field in the Inspector panel by exposing the field.

Components can use the gameObject property inherited from the base class to directly access the game object where the script is located, similar to transform.

gameObject: directly obtain the game object where the current component is located;

transform: The transform component of the game object where the component is located.

Common properties and methods of GameObject

Attributes:

  1. name : the name of the game object, which is the same as in the hierarchy panel;
  2. tag : the tag of the game object;
  3. activeInHierarchy : Whether it is display status;
  4. transform : the transform component of this game object;
  5. static GameObject Find (string path) : A static method to find game objects.

method:

  1. GetComponent<T> (): Get the components on the game object, T represents the type to be found, there are many similar methods;
  2. SetActive(bool) : Modify the display status.

7. Prefab Prefab

The concept of prefabs: prefabricated game objects.

Creation of prefabs:

​ Drag the game object directly into the project panel , and Unity will automatically generate a prefab for us.

Use of preforms:

​ Drag the prefab from the project panel to the hierarchy panel to achieve the effect of reuse .

  • The game objects created based on the prefab are relatively close to the " reference relationship ". When we modify the prefab, it will directly cause the game objects in the scene to change.
  • If the prefab is deleted, it will not affect the game objects in the game , but the game object will turn red in the hierarchy panel, which means that the prefab has been deleted. We can right-click in the hierarchy panel to cancel this reference relationship, so that the game The object becomes a normal game object.
  • The modification of the prefab is special , and you need to double-click to enter the "different world" for editing.

Modifications to the prefab:

​ Prefabs can be nested, that is, prefabs nest prefabs. Prefab modifications cannot be undone.

Variants:

​ During the process of creating a prefab, if the game object is already a prefab , Unity will pop up a window to remind us to choose the creation mode, namely:

  1. Primitive Prefab: a completely independent prefab;
  2. Prefab Variant: When the old prefab changes, the variant will also change, but the variant retains the parts that are different from the old prefab.

(create an original prefab from a prefab, the original prefab changes, both prefabs change; and create a prefab variant from this prefab, the variant changes, the prefab does not change, the prefab changes , the variant will change)

8. Unity lifecycle functions

Concept: In unity, it refers to the whole process of a component from activation to destruction.

Common lifecycle functions:

Awake(): Wake up event, executed at the beginning, only executed once .

OnEnable(): The event is enabled, executed once each time it is enabled. Executed every time the script component is enabled .

Start(): Start event, execute once .

FixedUpdate(): Fixed update event, executed N times, every 0.02 seconds . All physics related updates are handled in this event.

Update(): Update event, executed N times, once per frame , will be affected by the frame rate.

LateUpdate(): Update the event later , execute N times, and execute it after the Update () event is executed .

OnDisable(): Disable event, execute once every time it is disabled . The OnDestroy() event will also execute.

OnDestory(): Destroy event, execute once . Executed when the component is destroyed.

(The order of the above life cycle functions is the order of the Unity life cycle)

9. Invoke function

Invoke( ) function: used to call and execute a specific method within a specific time interval

Common execution methods of the Invoke function :

// 输入一个方法名称,过几秒来执行一次
Invoke(string methodName, float time){}

// 重复调用
InvokeRepeating(string methodName, float time, float repeatRate){}
    
// 取消调用,使用无参重载就是取消全部调用
CancelInvoke(string methodName){}
    
/*
    methodName:表示方法名称;
    time:表示几秒后执行;
    repeatRate:表示重复间隔时间。
*/

10. Coroutines

The concept of coroutines:

Coroutines are "coroutines" and are not equivalent to multithreading . The essence of coroutines is iterators .

In Unity, a coroutine is a function that can suspend the execution of the coroutine, return to the main function immediately after the pause, execute the rest of the main function, and continue to execute the rest of the coroutine from the next line of the interrupt command until the interrupt command is completed.

The function body is completely executed, and the coroutine ends. Due to the emergence of interrupt instructions, a function can be divided into multiple frames for execution.

Coroutine usage scenarios:

  1. delay calling a function;
  2. A certain piece of logic needs to be judged and executed in a loop.

Why do you need coroutines?

The main program is already executing a certain task and hopes to "run" other logics at the same time. The simultaneous here is not the same in the sense of multi-threading, but the sensory simultaneous.

How to define a coroutine function:

public IEnumerator Demo()  // 协程特定返回值IEnumerator
{
    Debug.Log("具体操作1");
    yield return new WaitForSeconds(1.0f);  // 等待一秒
    Debug.Log("具体操作2");
    // 协程不会因为前面返回则不执行后面的代码
}

public void Start()
{
    // 调用协程函数的两种方式
    StartCoroutine(Demo());
    StartCoroutine("Demo");
}

Stop coroutine function:

If the coroutine runs to the last line, it means to stop, but if we want to actively stop, use the following method.

 // 结束全部协程
StopAllCoroutines();
// 结束某个协程用 StopCoroutine
// 和调用协程一样使用,但是如果协程有参数不要使用这个
StopCoroutine(IEnumerator routine); 
// 参数填写协程变量
Coroutine routine = StartCoroutin(Demo());
StopCoroutine(Coroutine routine);
// 参数填写协程方法名
StopCoroutine(string methodName); 

11. Common tools

Math tools
  1. Mathf.Abs(int num): return the absolute value ;

  2. Mathf.Max(int a, int b): return a larger value (unlimited number) ;

  3. Mathf.Min(int a, int b): returns the smallest value ;

  4. Mathf.Round(2.5f): Returns the rounded value (rounded to six, five to take an even number) ;

  5. Mathf.Ceil(2.5f): return the value rounded up ;

  6. Mathf.Floor(2.5f): Returns the value rounded down ;

  7. Random.Range(0, 5): Returns a random value within the range .

    (1) If it is an int overload : return a random value of 0-4 , including 0 and excluding 5;

    (2) If it is float overload : returns a random value from 0 to 5 , including 0 and including 5.

time tools

read only

  • Time.time: Indicates the time from the running of the game to the present , and the calculation will stop when the game is paused;
  • Time.deltaTime: Indicates the individual time from the previous frame to the current frame , in seconds;
  • Time.realtimeSinceStartup: Indicates the total time since the game started, which will increase even if paused, which is real time .

read and write

  • Time.timeScale: Time scaling , the default value is 1, if the setting is < 1, it means the time slows down, if the setting is > 1, it means the time is speeding up, 0 means the game pauses.

Guess you like

Origin blog.csdn.net/Dukenone/article/details/126904535
Recommended