当前位置:网站首页>Unity foundation 1 - event execution sequence, custom events
Unity foundation 1 - event execution sequence, custom events
2022-07-28 20:55:00 【W.C.Zeng】
Sequence of events
stay unity in , We control the behavior of objects by adding scripts , It is very important to understand the sequence of events in the script . For details, see Official documents

The most commonly used life cycle functions are :
Some code snippets come from B Stand on the teacher's 3DRPG Course Of playercontroller.cs and mousemanager.cs
Awake
for example , Get reference of component
void Awake()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
characterStats = GetComponent<CharacterStats>();
stopDistance = agent.stoppingDistance;
}
Or bind the current script to the game object , Do not delete when marked to switch scenes
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(this);
}
OnEnable
Bind handlers for some events
void OnEnable()
{
MouseManager.Instance.OnMouseClick += MoveToTarget;
MouseManager.Instance.OnEnemyClick += EventAttack;
GameManager.Instance.RegisterPlayer(characterStats);
}
Update
Handle the input of the game 、 State switching, etc
void Update()
{
isDead = characterStats.CurrentHealth == 0;
if (isDead)
{
GameManager.Instance.NotifyObservers();
}
SwitchAnimation();
lastAttackTime -= Time.deltaTime;
}
OnDisable
Unregister the handler for some events
void OnDisable()
{
MouseManager.Instance.OnMouseClick -= MoveToTarget;
MouseManager.Instance.OnEnemyClick -= EventAttack;
}
OnDestroy
protected virtual void OnDestory()
{
if (instance == this)
{
instance = null;
}
}
FixUpdate
For physical state update , The fixed frame interval makes the physical effect more realistic
LateUpdate
For camera following , Only the last frame needs to update the position of the camera , The previous few frames can only update the information such as the position of the object .
Custom events
Sometimes we need to be outside the life cycle events , Custom events , for example , When replacing the mouse with an image , Judge the clicked items by emitting rays from the image position , Define your own logic for handling mouse click events , Event name required OnMouseClick And the parameter types required by the event handler Vector3
Law 1 : Inherit UnityEvent<T> Generic classes , Define your own event class , The advantage is that the editor can be in inspector The window is adding an event handler , like UI Button The click event of the button is the same 
using UnityEngine.Events;
[Serializable]
public class EventVector3 : UnityEvent<Vector3> {
}
Declare custom events
public class MouseManager : Singleton<MouseManager>
{
RaycastHit hitInfo;
public EventVector3 OnMouseClick;
// Or use it directly UnityEvent
// public UnityEvent OnGameFinish;
...
}
Law two : Use Csharp Commission of Action Define your own events , The advantage is easy to use
public class MouseManager : Singleton<MouseManager>
{
RaycastHit hitInfo;
// public EventVector3 OnMouseClick;
public event Action<Vector3> OnMouseClick;
public event Action<GameObject> OnEnemyClick;
...
}
Bind and remove event handlers
void OnEnable()
{
MouseManager.Instance.OnMouseClick += MoveToTarget;
MouseManager.Instance.OnEnemyClick += EventAttack;
GameManager.Instance.RegisterPlayer(characterStats);
}
void OnDisable()
{
MouseManager.Instance.OnMouseClick -= MoveToTarget;
MouseManager.Instance.OnEnemyClick -= EventAttack;
}
Call event
void MouseControl()
{
if (Input.GetMouseButtonDown(0) && hitInfo.collider != null)
{
if (hitInfo.collider.gameObject.CompareTag("Ground"))
{
OnMouseClick?.Invoke(hitInfo.point);
}
else if (hitInfo.collider.gameObject.CompareTag("Enemy"))
{
OnEnemyClick?.Invoke(hitInfo.collider.gameObject);
}
else if (hitInfo.collider.gameObject.CompareTag("Attackable"))
{
OnEnemyClick?.Invoke(hitInfo.collider.gameObject);
}
else if (hitInfo.collider.gameObject.CompareTag("Protal"))
{
OnMouseClick?.Invoke(hitInfo.point);
}
}
}
The rest of the code , Is in the update Medium emission ray
void Update()
{
SetCursorTexture();
MouseControl();
}
void SetCursorTexture()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
// Toggle mouse mapping
switch (hitInfo.collider.gameObject.tag)
{
case "Ground":
Cursor.SetCursor(target, new Vector2(16, 16), CursorMode.Auto);
break;
case "Enemy":
Cursor.SetCursor(attack, new Vector2(16, 16), CursorMode.Auto);
break;
case "Protal":
Cursor.SetCursor(doorway, new Vector2(16, 16), CursorMode.Auto);
break;
default:
Cursor.SetCursor(arrow, new Vector2(16, 16), CursorMode.Auto);
break;
}
}
}
边栏推荐
- 不懂就问,快速成为容器服务进阶玩家!
- Unity performance optimization
- Want to draw a picture that belongs to you? AI painting, you can also
- Integrating database Ecology: using eventbridge to build CDC applications
- UE4 3dui widget translucent rendering blur and ghosting problems
- Introduction to redis II: RedHat 6.5 installation and use
- Algorithm interview high frequency problem solving guide [1]
- 第六七八次作业
- The average altitude is 4000 meters! We built a cloud on the roof of the world
- 什么是“安全感”?沃尔沃用它自己独特的理解以及行动来告诉你
猜你喜欢

什么是数据中台?数据中台带来了哪些价值?_光点科技

融合数据库生态:利用 EventBridge 构建 CDC 应用

UE4 3dui widget translucent rendering blur and ghosting problems

How can enterprises successfully complete cloud migration?

作业 ce

Redis入门一:Redis实战读书笔记

Redis的三种删除策略以及逐出算法

JS drag and drop alert pop-up plug-in
![[complete collection of common ADB commands and their usage (from a comprehensive summary of [wake up on Sunday)]](/img/63/91b53b0ba718537383a97df59fe573.png)
[complete collection of common ADB commands and their usage (from a comprehensive summary of [wake up on Sunday)]

Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
随机推荐
SQL audit tool self introduction owls
第六七八次作业
leetcode:2141. 同时运行 N 台电脑的最长时间【最值考虑二分】
7/27 训练日志(位运算+后缀数组)
GIS数据漫谈(六)— 投影坐标系统
The engineering practice of super large model was polished, and Baidu AI Cloud released the cloud native AI 2.0 solution
C reads the data in the CSV file and displays it after importing the DataTable
How do we do full link grayscale on the database?
Unity gets which button (toggle) is selected under togglegroup
H5 wechat shooting game source code
一个程序员的水平能差到什么程度?尼玛,都是人才呀...
About the title of linking to other pages
Space shooting Lesson 10: score (painting and writing)
Explain in detail the rays and radiographic testing in unity
Explain rigid body and collider components in unity
Explain mesh Collider in unity
C# 读取 CSV文件内数据,导入DataTable后显示
Unity package project to vs deploy hololens process summary
3D激光SLAM:LeGO-LOAM论文解读---简介部分
到底为什么不建议使用SELECT * ?