Get started with Unity [Familiar with the unity editor, C# script control components and some properties]


Unity learning reference documentation and development tools

☺ Unity’s official website documentation: https://docs.unity3d.com/cn/current/Manual/ScriptingSection.html

■ Learning methods:

First understand the overview of unity, quickly get to know the unity editor, and then focus on learning: game objects, components | C# scripts, prefabs, UI

☺During the learning process, you will find that in fact, Unity mainly uses c# for development.

因为在这个过程中,无非就是,对游戏对象通过挂载的C#脚本,修改一下组件的一些属性,控制一下激活之类的操作。到了UGUI,同样,也是通过挂载的C#脚本,监听到事件发生后,调用一下C#脚本定义的方法处理一下事件。

  • Unity quick start document: https://learn.unity.com/tutorial/she-zhi-3d-beginner?uv=2020.3&projectId=5dfa9a5dedbc2a26d1077ca8
  • Video [To get started quickly, it is recommended to follow the video to get started]: https://www.bilibili.com/video/BV1gQ4y1e7SS/
  • ★Key learning content: game objects, components | C# scripts, prefabs, UI [GUI]

■ Development tools:

unity、visual studio



1. Unity Overview

(1) What is Unity

Unity is a set of cross-platform game development tools with a complete system and editor. It can also be called a game engine. A game engine refers to some written reusable codes and various functional editors used to develop games. Unity currently has more than 50% game engine market share.

Game engine = reusable code + various development tools


(2) Unity engine advantages

1. Based on C# programming, 易上手、高安全性features

2. Unique 面向组件game development ideas make game development simpler and easier to reuse

3. Have a very mature所见即所得开发编辑器

4. Possess 良好生态圈, the mall contains a large number of mature functional scripts and resources

5. Powerful cross-platform features, you can create multi-platform games for PC, console, mobile phone, AR, VR, etc.


2、Unity Hub

Managing Unity projects. When there are multiple projects with different versions of Unity on the computer, management is more troublesome. You can manage different Unity hub projects through Unity hub.



3. Get to know the unity editor


(1) Unity restores the default window: Windows->Layouts->Default


(2) Project settings

  • Includes: physics, sounds, quality, editor settings, and more


(3) Global settings

  • Common settings of the editor


  • To extend the tool, set up the script and use visual studio to open it.


(4) Unity menu bar introduction

■ File: General operations of files [project/scene creation, saving, etc., and packaging projects]

■ EditEdit: copy, cut, paste and other operations

■ Assets: Create [scripts, scenes, animations, etc.], import and export, etc.

■ Game object GameObject: will actually be displayed in the game scene

■ Component: very important because unity is component-oriented

  • Components and game objects are inseparable. A game object can have multiple components attached to it.


■ Switching between 2d and 3d scenes:

  • Click 2D and it becomes a 3D scene


(5) When the unity project runs, the entire scene is run, not a single game object.

  • The unit of operation is the scene!



4. Common operations on game objects

(0) Toolbar for operations related to the transform attribute


(1) Stretching

  • reset to 000


(2) Hide or show game objects in the layer


(3) See the grid shape of the game object

  • In order to facilitate observation, Shaded Wireframe is generally selected.


(4) Select the game object: just click with the mouse


(5) Right click-Eye surround


(6) In hand mode, combined with the mouse wheel, you can drag to adjust distance and close for observation.

  • Enter hand mode, shortcut, directly press and hold the mouse wheel

  • Like right-click-eye surround, both are for better overall observation of game objects.


(7) Parent-child game objects. Changes in the coordinates of the parent game object will also change the coordinates of the child game objects.

  • A game object, the default coordinate position after creation, the default position is relative to the world coordinates, referred to as the world coordinate position.
  • If a game object becomes a child game object of another game object, then its coordinates are the relative position - [position relative to the parent game object], referred to as relative position.

  • The outermost game object


  • For the coordinate axis position of the parent and child game objects, the parent axis position defaults to the middle of the parent and child game objects:

  • You can set it as the axis, and the parent coordinate position can be returned to the parent game object.


  • Coordinate axes, global refers to world coordinates


(8) Unity packaging operation

  • Package images, model files [suffix is ​​.fbx] and other materials in unity

  • The packaged file type is Unity package file


(9) Labels and layers

  • Tag: Generally used by ourselves in the code to determine whether the game object is the game object we want.
  • Layer: It is a kind of classification made by Unity. After classification, you can filter and display the camera; for example, the camera will not display this layer, and for collision, this layer can not collide, etc. wait.



5. Components

(1) What is a component

Components are functions. If you need to add any functions to the game object, you only need to add components to it.

In Unity, game objects do not have any functions. If you want to add functions to them, you need to add components with that function to them, and each component is actually one 引擎内部的组件脚本or more自己编写的组件脚本 . In other words, a game object (GameObject) will contain multiple components (Component), and each component is a component script.

  • For example: if you add a gravity component to a game object, the game object will fall down.
  • Another example: transform is also a component.
  • Another example: the reason why a light is a light is because it has one more light component than others. Game objects actually come with some components by default. For example, the cube comes with the cube component, and the ball comes with the ball component.
  • A game object (outer layer of the layer) corresponds to a script. When the required function [component] does not exist, you need to manually write the script yourself!

(2) Manually write C# scripts

  • Manually add the C# script to the project

  • Additional script

The reason why each game object behaves differently is because the component scripts bound to them are different!


(3) Component life cycle

  • From Awake to OnDestroy:
  • After Awake, OnEnale is activated, and then Start
  • Change: Change Update-LateUpdate by frame, change FixedUpdate by fixed time frequency
  • Deactivate OnDisable: and activate OnEnable are a pair
  • Finally, if the component is deleted, OnDestroy will be executed.

▪ Activate OnEnale and deactivate OnDisable:


■ Execution order of script life cycle

  • If there are multiple scripts, test1.cs, test2.cs, test3.cs

  • The execution order of the script is: I want to execute all the Awake methods of test1.cs, test2.cs, and test3.cs [if you have to write the Awake method manually! ], then from test1.cs to test2.cs and finally to test3.cs to execute the next life cycle - activate OnEanale [If there is a situation where the OnEanale method is written manually! ], and then from test1.cs to test2.cs and finally to test3.cs to execute the next life cycle Start...

    ▷ The current life cycle starts with Awake, and is executed from the first script to the last script in the project every time.

    ▷ Then enter the next life cycle, and all scripts will execute the current life cycle from the first script to the last script in the project!

  • If you want to change the execution order of the life cycle between scripts in the project, you can set it in Edit->Project Settings->Script Execution Order.

    • The order of adding is wrong, just drag and drop to change it.



6. Prefabs and variants

(1) What is a prefab?

In fact, it means encapsulating the things done in the scene [independent game objects] into prefabs [generating a file].

  • The suffix of the prefab is .prefab

(2) Advantages of prefabricated bodies:


(3) The difference between prefabs and scene game objects:

① If you directly modify the prefab, the game objects in the scene will change simultaneously. But if only the game objects in the scene are directly modified, the prefab remains unchanged.

  • This includes hanging components directly on the prefab, and game objects in the scene will be mounted synchronously.

② If you want to modify the game objects in the scene, the prefab will change simultaneously:

  • Select "Open" mode

③ The game object in the scene has components mounted and wants to be mounted to the prefabricated body simultaneously:

  • Single mount:

  • Batch mounting: override is applied to prefabs in batches


(4) Quickly select prefabs through game objects in the scene


(5) Variations

Prefab variant: Generate a variant of the current game object, which will depend on the old prefab.
When the old prefab changes, the variants will change with it. However, if the variant changes, the prefab will not change.



7. Dynamically modify the properties of game objects

(1) The relationship between the game object and the mounted C# script:


(2) An attribute object is added to the class of the C# script, and the attribute object is associated with Unity’s game object.


(3) Instantiate game objects in the scene through prefabs

  • Result 1:


  • Result 2:


■ The contents of EmptyTest.cs are as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/**
 * EmptyTest 类是绑定在场景SamepleScene下的游戏对象Empty身上
 * 补充,课外小知识,C#的 Debug.Log 方法,其实就是相当于 前端项目的 console.log 方法,也就是开发过程中用于打印日志的
 */
public class EmptyTest : MonoBehaviour
{
    public GameObject Cube;
    //预制体
    public GameObject Prefab;


    // Start is called before the first frame update
    void Start()
    {
        //当前类的属性gameObejct就对应了unity当前脚本所绑定的游戏对象
        GameObject gameObject = this.gameObject;
        Debug.Log("gameObject: " + gameObject);
        Debug.Log("gameObject的名称:" + gameObject.name);
        Debug.Log("gameObject的标签:" + gameObject.tag);
        Debug.Log("gameObject的图层:" + gameObject.layer);
        Debug.Log("Empty下的Cude的name:" + Cube.name);//子物体的名称
        Debug.Log("Empty下的Cude的继承的父类的激活状态:" + Cube.activeInHierarchy);//子物体继承关系的激活状态【看所继承的父物体的激活状态】
        Debug.Log("Empty下的Cude的自身的激活状态:" + Cube.activeSelf);//子物体自身的激活状态
        Debug.Log("Empty的transform:" + transform.position);//位置
        Debug.Log("Empty下的Cude的transform:" + transform.Find(Cube.name).position);//位置
        //给游戏对象添加上组件,通过拿到游戏对象.AddComponent方法
        gameObject.AddComponent<MeshFilter>();
        Cube.AddComponent<AudioSource>();
        //获取其他组件【这个其他组件,其实就是排除掉Transform这个必须的组件后的其他组件】
        Debug.Log("Empty获取其他组件:" + GetComponent<BoxCollider>());
        Debug.Log("Cube获取其他组件:" + Cube.GetComponent<BoxCollider>());
        //从子物体身上获取组件
        // GetComponentInChildren<BoxCollider>();
        //从父物体身上获取组件
        //GetComponentInParent<BoxCollider>();

        //全局查找--细节,就是首字母大写了,小写的是属性
        //所谓的全局查找,其实就是对当前的C#脚本所处的场景SamepleScene下进行全局查找 
        GameObject testGameObject = GameObject.Find("TestGameObject");
        //还可以通过标签名获取到游戏对象
        GameObject testGameObejct2 = GameObject.FindWithTag("enemy");
        Debug.Log("testGameObject:" + testGameObject);
        Debug.Log("testGameObject2:" + testGameObejct2);
        //还可以设置游戏对象是否激活
        testGameObject.SetActive(false);//取消激活

        //需求:通过预制体,在场景中实例化出游戏对象
        //预制体的类型也是GameObject
        // Instantiate(Prefab);
        // 实例化出游戏对象,并且是当前挂载了C#脚本的游戏对象的子物体
        GameObject capsule = Instantiate(Prefab, transform);
        // 销毁游戏对象
        Destroy(capsule);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

8. Application classes needed to read and write files

(1) Application reads and writes files


(2) Application also has the function of controlling permissions, such as controlling the background running of the game, opening links, and exiting the game.


9. Game scene

■ Core class - scene management class SceneManager: related to scene creation, scene switching | loading, scene acquisition, scene number, and scene unloading


■ Common attributes about scenes: scene name, whether the scene has been loaded, scene path, scene index, independent game objects in the scene


■ Asynchronously load scenes and obtain progress

  • Through coroutine [coroutine is actually an assistance type of multi-threading] StartCoroutine (task);
  • Get the progress in Update, because Update outputs the changes of each frame


▷ Control scene jump through timer:



10、transform

(1) Position, rotation, scaling, vector


(2) transform other relationships


(2) transform parent-child relationship

The parent-child relationship of game objects is actually maintained through transform




11. Unity GUI (UGUI for short)

GUI: Graphical User Interface graphical user interface or graphical user interface.

  • GUI,是平面的,在2d下操作

  • Commonly used controls in UI

  • At its most basic 画布Canvas, UI is equivalent to a screen.

    • The most basic UI is the canvas. Other UI controls - Text, Image, Button, etc. are placed on the canvas as sub-controls of the Canvas.
  • The other most basic thing about UI is 事件系统EventSystemthat it actually encapsulates many common events, such as click events.


(1) Canvas, equivalent to screen

■ The rendering mode of the Canvas component generally defaults to screen space-coverage

  • The camera captures real game footage, 3D footage. The images captured by the camera will be rendered first.
  • UI overlay: It will be overlaid on the picture captured by the camera. Therefore, the UI can always be displayed on the top layer.
  • This is also consistent with most real game situations, where the UI is displayed on top of the game screen. For example, opening a backpack interface or character attribute interface cannot be covered by objects in the game scene, such as trees.


■ The zoom mode of the Canvas component is generally selected to scale according to the screen resolution

  • Canvas has been adapted. To really take effect, the first-layer sub-controls under Canvas also need to be adapted.

  • The first layer of sub-controls is adapted:

    • The anchor point is set on the parent object.

    • The role of the control anchor point: the control will always maintain a certain distance from the anchor point.


(2) Event binding: Take the UI of Button as an example

① Add UI-Button under Canvas, create a C# script under the project, and then mount the C# script on the Button

② Then in the C# method, write a processing method BtnClick() when a click event occurs

③ Finally, add the C# script to On Click() under the Button component, and the processing method BtnClick() when the click event occurs.


(3) Management UI components - panel Panel [layout, alignment, adapted axis point position, etc.]


(4) For some operation details of common GUI UI [text, button, slider, etc.], you can refer to the article:

  • Written in great detail - "Unity's UGUI System Foundation": https://blog.csdn.net/qq_42898629/article/details/83504863




If this article is helpful to you, remember to give Yile a like, thank you!

Guess you like

Origin blog.csdn.net/weixin_45630258/article/details/130140670