【Unity】Some learning records of unity/C#

Some records during the learning process

Article directory

Unity is a single-threaded core, so there is no need to consider threads, concurrency, and mutual exclusion.

Useful/useful links

Unity Script API
Unity Life Cycle
Detailed explanation of prefabs in Unity

About the arrangement of common c# commands

❀ Unity printing

Debug.Log("** **");

❀Tooltips (annotations)

[ Tooltip("角速度,每秒转动speed度")]
public float speed = 30f; 

Insert image description here

❀ Get relevant information about the current script binding

this.name   // 绑定模型名字
this.transform.position; // 绑定模型当前世界位置坐标
this.transform.localPosition;  // 绑定模型本地位置坐标(相对坐标
this.transform.eulerAngles;	// 绑定模型当前世界转角坐标
this.transform.localEulerAngles; // 绑定模型当前本地转角坐标
AudioSource audio = this.GetComponent<AudioSource>(); // 获取当前的AudioSource组件
this.transform.childCount;  // 获取子物体数量

❀ Get information about components of another node

Reference component

Get the AudioSource component

// 方法一
public GameObject bgmNode;  
void Start()
{
    
    
    AudioSource audio = bgmNode.GetComponent<AudioSource>();
    audio.Play();
}
// 方法二
public AudioSource bgm;
void Start()
{
    
    
    bgm.Play();
}

quoted script

// 方法一
public GameObject planetNode;
void Start()
{
    
    
    // 引用其他节点脚本
    PlanetLogic planet = planetNode.GetComponent<PlanetLogic>();
    planet.rotateSpeed = 10;
}
// 方法二
public PlanetLogic planet;
void Start()
{
    
    
    planet.rotateSpeed = 10;
}

❀ Set frame rate

 Application.targetFrameRate = 60;

❀ Get the target object

 // 获取层级物体(容易出错,不适应自动变化)
 GameObject capsule = GameObject.Find("胶囊"); 
 GameObject node = GameObject.Find("飞机盒子/机翼"); // 二级子节点应指定路径 
 // 检查器引用
 public GameObject node;

❀ Get the parent and child nodes of the current node

Get parent node

// 获取父级
Transform parent = this.transform.parent;
// 获取父级节点
GameObject parentNode = this.transform.parent.gameObject;

Debug.Log("父级节点" + parentNode.name);

Get child nodes

// 获取子级节点
// 方法一 遍历获取
foreach(Transform child in transform)
{
    
    
    Debug.Log("子级节点" + child.name);
}
// 方法二 按索引获取 
Transform aa = this.transform.GetChild(0);
Debug.Log("子级节点aa=" + aa.name);
// 方法三 按名字查找
Transform a = this.transform.Find("c");
Transform b = this.transform.Find("b");
Transform c = this.transform.Find("b/bb");  // 二级子节点应指定路径       

❀ Move to new node

Move under new parent

// 从根节点下查找
Transform p2 = this.transform.Find("/parent1");
// 移动到新父级节点
this.transform.SetParent(p2);

Set as first-level node (no parent node)

// 设为一级节点(没有父级)
this.transform.SetParent(null);

Operate objects to show/hide nodes

(three different objects)

// 找到要显示/隐藏的节点
Transform child = this.transform.Find("b");
// 判断当前显示状态
if(child.gameObject.activeSelf)
{
    
    
    // 禁用
    child.gameObject.SetActive(false);
}
else
{
    
    
    // 启用
    child.gameObject.SetActive(true);
}

❀Move forward at a constant speed

// 匀速每秒speed米运动
float speed = 2; 
float distance = speed * Time.deltaTime;
// 蟹老板每秒向前移动
//Vector3 pos = this.transform.localPosition;
//pos.z -= distance; // 0.02f;
//this.transform.localPosition = pos;
// 相对运动  transform.Translate(dx, dy, dz, space) space: Space.World--世界坐标  Space.Self--本地坐标(自身坐标)
this.transform.Translate(0, 0, distance, Space.Self);

❀ Rotations per second

turn

// 获取当前转角
Vector3 angles = this.transform.localEulerAngles;
// 蟹老板每秒旋转
//angles.y += 0.5f;
//this.transform.localEulerAngles = angles;

float rotateSpeed = 60; // 角速度,每秒转动60度
this.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0 ,Space.Self);

Earth-moon system (rotation and revolution)

Insert image description here

// 地球
void Update()
    {
    
    
        float rotateSpeed = 10; // 角速度,每秒转动60度角
        //按y轴旋转 自转
        this.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0, Space.Self);
    }
// 月球
void Update()
    {
    
    
        float rotateSpeed = 60;
        // 查找该物体的父物体
        Transform parent = this.transform.parent;
        parent.Rotate(0, rotateSpeed * Time.deltaTime, 0, Space.Self);
    }

❀ Resource array

(Three different things under the same object)

Shuffle music

Code:

    // 定义一个数组变量
    public AudioClip[] clips;
    // Start is called before the first frame update
    void Start()
    {
    
    
        if (clips == null || clips.Length == 0)
        {
    
    
            Debug.Log("请添加音乐");
            return;
        }
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            NextSong();
        }
    }

    private void NextSong()
    {
    
    
        // 随机播放
        int index = UnityEngine.Random.Range(0, clips.Length);

        AudioSource source = GetComponent<AudioSource>();
        source.clip = clips[index];
        source.Play();
        Debug.Log("歌名" + clips[index].name);
    }

Detector:
Insert image description here

color changing ball

    public Material[] colors;
    int index = 0;
    public float speed = 1.5f; // 小球的速度

    // Start is called before the first frame update
    void Start()
    {
    
    
        Debug.Log("Start =.=");
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
         	// 变色
            ChangeColor();
            if (IsInvoking("DoSomething"))
            {
    
    
                // 取消单个定时调用
                CancelInvoke("DoSomething");
                Debug.Log("Stop 0.0");
            }
            else
            {
    
    
                this.InvokeRepeating("DoSomething", 1, 2);
            }
        }

        // 移动
        this.transform.Translate(0, speed * Time.deltaTime, 0, Space.Self);
    }
    private void DoSomething()
    {
    
    
        Debug.Log("DoSomething. >.<" + Time.time);
        speed = 0 - speed;
    }
    private void ChangeColor()
    {
    
    
        index++;
        if(index >= colors.Length)
        {
    
    
            index = 0;
        }
        Material color = colors[index];
        MeshRenderer mr = GetComponent<MeshRenderer>();
        mr.material = color;
    }

❀ Exit the game/program

Implement exit game function in Unity

    public void ExitGame()
    {
    
    
        #if UNITY_EDITOR
            //退出编辑器模式
            UnityEditor.EditorApplication.isPlaying = false;
        #else
            // 退出程序
            Application.Quit();
        #endif
    }

Commonly used preprocessing identifiers

identifier explain
UNITY_EDITOR Only compile in editor
UNITY_ANDROID Compile only under Android
UNITY_IPHONE Only compiled under Apple system
UNITY_STANDALONE_OSX Definitions specifically for Mac OS (including Universal, PPC and Intelarchitectures) platforms
UNITY_STANDALONE_WIN Compile only under Windows system

❀ Game pause/resume

Unity game pause and resume

Time.timeScale time scaling

Pause: Time.timeScale = 0
Continue: Time.timeScale = 1

❀ Dynamically create empty GameObject

GameObject menuGroup = new GameObject("MenuGroup");
menuGroup.transform.parent = transform;
menuGroup.AddComponent<Menu>();

❀ Read file text

File.ReadAllText

Note: Start searching for the path from the current project. The path must be written in full, otherwise an error will be reportedCould not find a part of the path “D :\Resources\Jsons\menuData.json”.

string str = File.ReadAllText("Assets/Resources/Jsons/menuData.json");

Resources.Load

Through the Resources.Load function, you can access all resources in the folder named "Resources" anywhere in the Assets folder
Note: The Resources folder in Assets needs to be created before use

//使用指定文本内容创建一个新 TextAsset
TextAsset menuJson = Resources.Load<TextAsset>("Jsons/menuData");

❀ JSON serialization

Convert JSON back to object (JsonUtility.FromJson)

JsonUtility.FromJson _ UnityApi

SimpleJson

1. json file
Note: The json must be saved in utf-8 and unsigned, otherwise an error will be reported

// .json
{
    
    
    "name":"推荐",
    "icon":"Icons/activity",
    "icon1":"Icons/activity1"
}

2. Create a Class instance to store fields
Note: The Serializable attribute tag must be used

// TestArr.cs
[System.Serializable]  // 重点
class TestArr 
{
    
    
    public string name;
    public string icon;
    public string icon1;
}

3. Convert JSON back to object

// Menu.cs
// 简单Json
TextAsset testJson = Resources.Load<TextAsset>("Jsons/testData");
TestArr testArr = JsonUtility.FromJson<TestArr>(testJson.text);
Debug.Log(testArr.name);
Complex Json

1. json file
Note: The json must be saved in utf-8 and unsigned, otherwise an error will be reported

//.json
{
    
    
    "menuData":[
        {
    
    
            "id":0,
            "name":"推荐",
            "icon":"Icons/activity",
            "icon1":"Icons/activity1"
        },
        {
    
    
            "id":1,
            "name":"我的喜欢",
            "icon":"Icons/activity",
            "icon1":"Icons/activity1"
        }
    ]
}

2. Create a Class instance to store fields
Note: 1. The Serializable attribute tag must be used
2. Note that the keys of json are exactly the same as the fields of the custom class, otherwise the data cannot be read

// MenuArr.cs
[System.Serializable] // 记得添加,否则转换不了
 class MenuArr 
{
    
    
    public List<MenuList> menuData; //注意json的键和自定义的类的字段完全一致,否则读不到数据
}

[System.Serializable]  // 记得添加,否则转换不了
class MenuList
{
    
    
    public string id;
    public string name;
    public string icon;
    public string icon1;
}

3. Convert JSON back to object

 void Start()
    {
    
    
        // 另一种读取文本文件方法 
		//string str = File.ReadAllText("Assets/Resources/Jsons/menuData.json");
		//MenuArr menuArr1 = JsonUtility.FromJson<MenuArr>(str);
		
		//使用指定文本内容创建一个新 TextAsset
		TextAsset menuJson = Resources.Load<TextAsset>("Jsons/menuData");
		MenuArr menuArr = JsonUtility.FromJson<MenuArr>(menuJson.text);
		
		for (int i = 0; i < menuArr.menuData.Count; i++)
		{
    
    
		   Debug.Log(menuArr.menuData[i].name);
		}
    }

❀ Dynamically use Json data path

Parse Json, see aboveConvert JSON back to object

 Resources.Load<Sprite>($"{
      
      menuArr.menuData[i].icon}"); 

Unity life cycle

Please see the useful links for details Unity Life Cycle and UnityAPI: MonoBehaviour

❀ Awake

Execute only once
Called whenever the object is loaded, regardless of whether the script is available or not
Always at any time Called before the Start method and after instantiating the prefab

❀ Start

Executed only once
Called when the object is loaded and the script object is enabled
Start is only called before the Update function is called for the first time, and Will only be called once when the script instance is enabled

❀ Update (Frame Update)

Called once per frame

❀OnEnable (when available)

Can be called multiple times
This function is called when the object becomes available or activated

❀OnTriggerXXX (trigger)

Called when the trigger is fired.

OnTriggerEnter

Unity calls OnTriggerEnter when GameObject collides with another GameObject.
Touch conditions:
One of the two parties must set Is Trigger to Enable.
Insert image description here
One of both parties must have a Rigidbody component.
Function:

    private void OnTriggerEnter(Collider other)
    {
    
    
        Debug.Log("***子弹碰撞*** other = " + other.name);

        //检测名字是否以xxx开头
        if (! other.name.StartsWith("SlimePBR"))
            return;

        // 销毁节点
        // 自毁
        Destroy(gameObject);
        // 销毁怪兽
        Destroy(other.gameObject);
    }

Unity regularly calls the Invoke series

Call the invoke series functions regularly, which is generally called timer
Avoid repeated use when using it

Inherited fromMonoBehaviour

Invoke

public void Invoke (string methodName, float time)
在 time 秒后调用 methodName 方法。只调用一次

void Start()
    {
    
    
        Debug.Log("Start =.=");
        // 一秒后执行
        this.Invoke("DoSomething", 1);
    }
private void DoSomething()
    {
    
    
        Debug.Log("DoSomething. >.<" + Time.time);
    }

Insert image description here

InvokeRepeating

public void InvokeRepeating( string methodName, float < /span>Loop call The methodName method is called after time seconds and then every repeatRate seconds. ): repeatRate, float time

    void Start()
    {
    
    
        Debug.Log("Start =.=");
        // 1秒后执行,之后每隔2秒执行一次
        this.InvokeRepeating("DoSomething", 1, 2);
    }
	private void DoSomething()
    {
    
    
        Debug.Log("DoSomething. >.<" + Time.time);
    }

Insert image description here

IsInvoking

public bool IsInvoking ( string methodName )
Are there any pending methodName calls

//判断是否调用
if (IsInvoking("DoSomething"))
{
    
    
    // 取消单个定时调用
    CancelInvoke("DoSomething");
}
else
{
    
    
    this.InvokeRepeating("DoSomething", 1, 2);
}

CancelInvoke

public void CancelInvoke ( )
Cancel all Invoke calls on this MonoBehaviour

// 取消单个定时调用
CancelInvoke("DoSomething");
// 取消所有定时调用
CancelInvoke();

Case

traffic light

    [Tooltip("红绿黄按顺序")]
    public Material[] colors;

    int index = 0; // 从红灯开始
    
    void Start()
    {
    
    
        ChangeColor();
    }
    void ChangeColor()
    {
    
    
        // 当前材质
        Material color = colors[index];
        MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
        meshRenderer.material = color;

        if(index == 0)
        {
    
    
            Invoke("ChangeColor", 4);
        }
        else if(index == 1)
        {
    
    
            Invoke("ChangeColor", 4);
        }else if(index == 2)
        {
    
    
            Invoke("ChangeColor", 1);
        }

        // 切换
        index++;
        if(index >= colors.Length)
        {
    
    
            index = 0;
        }
    }

Acceleration and deceleration

    [Tooltip("最大转速")]
    public float maxSpeed = 720;
    
    float speed = 0; // 当前转速
    bool isSpeedUp = false; // 是否加速

    // Start is called before the first frame update
    void Start()
    {
    
    
        InvokeRepeating("AdjustSpeed", 0.1f, 0.1f);
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            isSpeedUp = !isSpeedUp;
        }

        // 旋转
        if(speed > 0)
        {
    
    
            this.transform.Rotate(0, speed * Time.deltaTime, 0, Space.Self);
        }
    }
    void AdjustSpeed()
    {
    
    
        // 是否处于加速状态
        if (isSpeedUp)
        {
    
    
            if(speed < maxSpeed)
                speed += 10;
        }
        else
        {
    
    
            speed -= 10;
            if(speed < 0)
                speed = 0;
        }
    }

unity vector

Vector3

❀ Get the vector length magnitude

Vector3 v = new Vector3(3, 0, 4);
// 获得三维向量长度
float len = v.magnitude;
Debug.Log("长度=" + len);

❀Normalized to unit vector normalized

Vector3 v1 = new Vector3(2, 2, 0);
 // 标准化为单位向量(长度为1的向量)
Vector3 v2 = v1.normalized;
Debug.Log(v1.ToString("f3") + "v1长度=" + v1.magnitude);
Debug.Log(v2.ToString("f3") + "v2长度=" + v2.magnitude);

Insert image description here

❀ Constants (static variables)

Vector3.xx Remark
back Convenient way to write Vector3(0, 0, -1).
down Convenient way to write Vector3(0, -1, 0).
forward Convenient way to write Vector3(0, 0, 1).
left Convenient way to write Vector3(-1, 0, 0).
negativeInfinity Convenience method for writing Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity).
one Convenient way to write Vector3(1, 1, 1).
positiveInfinity Convenience method for writing Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity).
right Convenient way to write Vector3(1, 0, 0).
up Convenient way to write Vector3(0, 1, 0).
zero Convenient way to write Vector3(0, 0, 0).

❀ Vector operations

addition

Insert image description here

Subtraction

Insert image description here

multiplication

Vector multiplication is divided into 3 types:

  • Scalar multiplication b = a * 2
  • Dot product c = Vector3.Dot ( a, b )
  • shape c = Vector3.Cross(a,b)

❀ Assignment

Insert image description here

❀ Vector ranging

Find the distance between two objects

// 获取当前位置
Vector3 p1 = this.transform.position;
Vector3 p2 = capsule.transform.position;
// 计算间距
Vector3 p = p2 - p1;
float dist = p.magnitude;  // 两个物体间距离
Debug.Log("两个物体间距离:" + dist);
  • Vector3.Distance
    Returns the distance between a and b.
    Vector3.Distance(a,b) is the same as (a-b).magnitude.
// 获取当前位置
Vector3 p1 = this.transform.position;
Vector3 p2 = capsule.transform.position;
// 计算间距
float dist = Vector3.Distance(p2, p1); // 两个物体间距离
Debug.Log("两个物体间距离:" + dist);

Unity prefab Prefab

Detailed explanation of prefabs in Unity
The role of prefabs is to reuse resources, so objects that are reused in the scene should be made into prefabs as much as possible and then dragged into the game. Use

When exporting prefab resources, dependency files should be exported together.
prefab only records node information.
The prefab file does not contain material and texture data, only references

✿ Make prefabs

Drag objects directly from the Hierarchy into Assets
Insert image description here

✿ Packaging prefabs

1. Right-click and select Package
Insert image description here
2. Select dependencies (check Include dependencies)
Insert image description here
3. Export

✿ Prefab instance

Prefab Instance, an object created from a prefab
When the prefab resource changes, the prefab instance will also change synchronously
Features:

  • In Hierarchy, node icons are different
  • In Hierarchy, right-click menu|Prefab
  • In Inspector, Context Tools | Prefab

Unlock a prefab instance and turn it into a normal object

Select the prefab instance to be removed and right-click
Insert image description here

✿ Edit prefab

*.prefab is equivalent to a template and can be edited again

Method 1: Edit alone

1. Double-click Prefab to enter individual editing mode - edit nodes and components
Insert image description here

2. Exit and complete editing
Exit 1: Click Scenes
Insert image description here
Exit 2: Click Return
Insert image description here

Method 2: Edit in situ

1. Select Prefab lnstance (prefab instance)
Insert image description here
2. Open in the inspector
Insert image description here
or
Insert image description here

3. Context display: Normal / Gray / Hidden
Insert image description here

At this time, only the selected objects are edited, and the remaining objects are foil-editing nodes.
Insert image description here

4. Exit and complete editing

Method 3: Overwrite editing

1. Select Prefab Instance
2. Edit directly in the scene - after editing
Overrides | Apply, apply the edit< a i=3> Overrides | Revert, cancel editing

Insert image description here

✿ Script searches for prefabs and creates prefabs

Place the prefab in the Assets/Resouces directory

    void Start()
    {
    
    
        var findMainObj = GameObject.Find("MusicUIProject/MusicUIMainPage");
        if (findMainObj == null)
        {
    
    
        	// 查找预制体
            GameObject mainObj = Resources.Load<GameObject>("Prefabs/Pages/MusicUIMainPage");
            // 添加预制体
            mainObj = Instantiate(mainObj, transform);
            // 修改预制体名字
            mainObj.name = "MusicUIMainPage";
        }
        Debug.Log(findMainObj);
    }

✿ Dynamically create prefab instances

Object.Instantiate: Clone the original object and return the cloned object.

	// 对子弹prefab引用
    public GameObject bulletPrefab;

    // Start is called before the first frame update
    void Start()
    {
    
    
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            TestFire();
        }
    }

    private void TestFire()
    {
    
    
        Debug.Log("创建子弹");
        //克隆 original 对象并返回克隆对象
        // (预制体节点,父节点路径) null:在根节点下
        GameObject node = Object.Instantiate(bulletPrefab, null); 
    }

✿ Initialize prefab instance

(1) Transform is generally referenced, but GameObject has no sense of existence
(2) You can use an empty object to mark a spatial coordinate

After creating the Prefab Instance, initialization should be done

  • parent , parent node
// 引用子弹树 Transform 节点   获取实例根目录
public Transform bulletFolder;
...
private void TestFire()
{
    
    
	Debug.Log("创建子弹");
	//克隆 original 对象并返回克隆对象
	// (预制体节点,父节点路径)
	GameObject node = Object.Instantiate(bulletPrefab, bulletFolder); 
	...
}

Insert image description here

  • position / localPosition ,point
  • eulerAngles/localEulerAngles, rotate
private void TestFire()
{
    
    
    ...
    node.transform.position = Vector3.zero;
    node.transform.localEulerAngles = new Vector3(-90, 0, -90);
}

or

// 引用子弹出生的Transform节点 获取实例的出生位置
public Transform firePoint;
// 引用坦克Transform节点  获取实例的旋转角度
public Transform tank;
...
private void TestFire()
{
    
    
    ...
    // 指定子弹出生的位置   (使用世界坐标
    node.transform.position = this.firePoint.position;
    // 指定子弹出生的旋转角度(随炮台  (使用世界坐标
    node.transform.eulerAngles = this.tank.eulerAngles;
    //node.transform.rotation = this.tank.rotation;
}
  • Script, the built-in control script
    private void TestFire()
    {
    
    
		...
        // 获取接口
        BulletLogic bulletLogic = node.GetComponent<BulletLogic>();
        // 设置子弹的速度参数
        bulletLogic.speed = 5f;
    }

Prefab
Insert image description here

✿ Destroy the prefab instance

Object.Destroy: Remove GameObject, component or resource.
Destroy() will not be executed immediately, but will be executed after this round of Update

	void Start()
    {
    
    
    	// 延时销毁
        Invoke("SelfDestroy", 100);
    }
    // 自毁
    private void SelfDestroy()
    {
    
    
        Debug.Log("销毁了");
        Destroy(this.gameObject);
    }

Prefabs and variant prefabs

Insert image description here

unity physics system Physics

Insert image description here

❀ Add Rigidbody

When a Rigidbody is added, the object engine is responsible for the movement of the rigid body.

Component Physics | Rigidbody
Insert image description here
Insert image description here
Mass: Quality
Drag
Angular Drag
Use Gravity: Use gravity
ls Kinematic: Whether it is a kinematic rigid body
lnterpolate
Collision Detection: Collision detection lnfo
Constraints

❀Physical Collision Collider

Collider Collider, describes the collision range of the object.
Among them,
Box Collider, rectangular collision body
Sphere Collider, spherical collision body
Insert image description here

Insert image description here

❀ Rebound and friction of rigid bodiesPhysic Material

1. Right-click to create a new physical material - create - Physic Material
Insert image description here
2. Panel
Insert image description here
Dynamic Friction: Dynamic friction
Static Friction: static friction
Bounciness: bouncing force
Friction Combine
Average
Bounce Combine
Average
3. Use material
Drag the material to material
Insert image description here
Insert image description here

❀ Physical collision detection

OnTriggerEnter

Unity calls OnTriggerEnter when GameObject collides with another GameObject.
Touch conditions:
One of the two parties must set Is Trigger to Enable.
One of both parties must have a Rigidbody component.

    private void OnTriggerEnter(Collider other)
    {
    
    
        Debug.Log("***子弹碰撞*** other = " + other.name);

        //检测名字是否以xxx开头
        if (! other.name.StartsWith("SlimePBR"))
            return;

        // 销毁节点
        // 自毁
        Destroy(gameObject);
        // 销毁怪兽
        Destroy(other.gameObject);
    }

❀ CharacterController

Reference CharacterController and UintyApi: CharacterController

  • Character controllers allow you to more easily handle motion with collisions without having to deal with rigid bodies. (That is to say, the character controller is responsible for handling the movement of the character. If you add a character controller, you do not need to add a rigid body component)
  • The character controller is not affected by forces and will only move when you call the move function. His movement is subject to collision.
    CharacterController cc;
    void Start()
    {
    
    
        cc = GetComponent<CharacterController>();
    }

    // 移动
    public void Move(Vector3 v)
    {
    
    
        Vector3 movement = v * speed;
        cc.SimpleMove(movement);
    }

CharacterController.velocity (the character's current relative velocity)

unity switch scene

switch scene

1. Add scene
Insert image description here

2. Build the scene
Insert image description here
3. Add a script to the button to jump to the scene
Insert image description here

using UnityEngine.SceneManagement;
...
    public void ToScene()
    {
    
    
        SceneManager.LoadScene("NewScene");
        //SceneManager.LoadScene(1);
        Debug.Log("跳转");
    }

Switch scenes and transfer parameters at the same time

Transmitting data between Unity scenes (Scene)
How to transfer and save data when switching between Unity scenes

Scenario A passes parameters to Scenario B

  • Scenario A
    1. Add a jump event in script A that triggers a jump event (clicking a button or disappearing a character, etc.)
	// 按钮事件
	 public void ToScene()
    {
    
    
        SetScene(1233);
    }
	// 传参跳转
    void SetScene(int data)
    {
    
    
    	// 赋值
        GameObject.Find("gameData").GetComponent<GameData>().param = data;
        // 场景切换 
        SceneManager.LoadScene(2);
    }

2. Create an empty object EmptyObject in scene A and name it gameData
Insert image description here
❗There is only one gameData in the entire game, and it is the same one, guaranteed to be initialized only once

Mount the script GameData on gameData

    public static GameData instance;
    // 保存的数据
    public int param;

    private void Awake()
    {
    
    
        if(instance == null)
        {
    
    
            DontDestroyOnLoad(gameObject);
            instance = this;
        }
        else if(instance != null)
        {
    
    
            Destroy(gameObject);
        }
             
    }
  • Scenario B
    Mount script B on an empty node or a required node
    void Start()
    {
    
    
        int param = GameObject.Find("gameData").GetComponent<GameData>().param;
        // 验证参数获取
        Debug.Log(param);
    }

Delay jump scene

Timer Invoke

    void Start()
    {
    
    
        Invoke("ToSecene", 0.5f);
    }
    
    void ToSecene()
    {
    
    
        SceneManager.LoadScene(2);
    }

Coroutine StartCoroutine

Please refer to
Coroutine
Create screen transition

The object cannot call the coroutine when it is inactive (hidden/invisible).

    void Start()
    {
    
    
        StartCoroutine("ToSecene");
    }
    
    IEnumerator ToSecene()
    {
    
    
        yield return new WaitForSeconds(0.5f); // 暂停协程,1秒后执行之后的操作
        Debug.Log("111");
        SceneManager.LoadScene(2);
    }

Unity custom input

customize

Open [Edit]->[Project Setting]->[Input] in the menu bar
Insert image description here
Insert image description here

❤ Input.GetButtonDown: (customized virtual button)

Returns true during the frame in which the user presses the virtual button identified by buttonName.

use

        // 按下虚拟按钮时触发
        if (Input.GetButtonDown("Fire1"))
        {
    
    
            character.Attack();
        }

❤ Input.GetAxis:

Returns the value of the virtual axis identified by axisName.

use

unity skybox

1. Lighting settings
Insert image description here
2. Select sky box material
Insert image description here

Import local resource package

To import a local resource pack in Unity:

1. Open the project into which you want to import the resource package in the Editor.

2. Download Assets > Import Package > Custom Package.
Insert image description here

A file browser appears, prompting you to find the .unitypackage file.

3. In the file browser, select the file to import and click Open.

Unity script execution order

Calling sequence

Insert image description here
The order in which Unity calls Awake for each GameObject isundefined

priority

The default execution priority of all scripts is0
The execution order of scripts has nothing to do with the hierarchical order in Hierarchy
Generally, there is no need to explicitly set the Execution Order default


Set priority:
1 Select a script to open the Execution Order dialog box
2 Click the + button to add a script
3 Specify the priority. The smaller the value, the higher the priority. Or, drag directly to adjust the order
Insert image description here

Main control script

1. Set up an empty node and add the main control script
Insert image description here
Insert image description here

After adding, you can reference other components, etc.

About the problems encountered in learning unity

✎ VS reports an error using unity statement

When using Debug.Log("First Script");, an error is reported directly. After checking, it is found that unity has no link to the vs editor
Solution: Unity panel Edit - Preferences
Insert image description here

✎ CS1503: Parameter 1: Cannot convert from "double" to "float"

pos.z += 0.02;  // 报错写法
pos.z += 0.02f;	 // 正确写法

✎ No Sprite Editor Window registered.Please download2D Sprite package from Package Manager.

Insert image description here
Solution: Unity Panel Windows - Package Manager Download
Switch to Packages: Unity Registry and select Install
Insert image description here

✎ Dropdown获取失败 NullReferenceException: Object reference not set to an instance of an object

Insert image description here
Solution: Wrong component used
Insert image description here

✎ UnassignedReferenceException: The variable bulletPrefab of FireLogic has not been assigned.

Problem: Checker exists but no value assigned
Insert image description here
Solution: Assignment

✎ 场景切换问题:Scene ‘NewScene’ couldn’t be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.

Insert image description here

Solution:
1. Select the build scenario
Insert image description here
2. Add all required scenarios
Insert image description here

✎ 协程报错:Coroutine ‘XXX’ couldn’t be started because the the game object ‘XXXX’ is inactive!

Coroutines cannot be called when an object is inactive (hidden/invisible).

The error reference link

Guess you like

Origin blog.csdn.net/qq_36687211/article/details/127683692