当前位置:网站首页>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;
}
}
}
边栏推荐
- Learn about the native application management platform of rainbow cloud
- How to balance security and performance in SQL?
- C# 读取 CSV文件内数据,导入DataTable后显示
- Yum package management
- Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~
- Unity typewriter teaches you three ways
- Interpretation of ue4.25 slate source code
- 到底为什么不建议使用SELECT * ?
- Dynamic planning: code summary of knapsack problem template
- Explain mesh Collider in unity
猜你喜欢

prometheus配置alertmanager完整过程

Explain in detail the rays and radiographic testing in unity

Three steps to teach you unity serial communication

How do we do full link grayscale on the database?

How bad can a programmer be? Nima, they are all talents

有奖征文 | 2022 云原生编程挑战赛征稿活动开启

Unity gadget displays the file size of the resource directory

Explain the imported 3D model in unity

JS fly into JS special effect pop-up login box
Looking at SQL optimization from the whole process of one query
随机推荐
Introduction to redis II: RedHat 6.5 installation and use
What is data center? What value does the data center bring_ Light spot technology
Ask if you don't understand, and quickly become an advanced player of container service!
华为云数字资产链,“链”接数字经济无限精彩
Explain rigid body and collider components in unity
动态规划:背包问题模板代码汇总
leetcode:2141. 同时运行 N 台电脑的最长时间【最值考虑二分】
网络各层性能测试
3D laser slam: Interpretation of logo-loam paper - Introduction
企业如何成功完成云迁移?
LVS+KeepAlived高可用部署实战应用
Unity gadget displays the file size of the resource directory
Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
JS chart scatter example
Nat experiment demonstration (Huawei switch equipment configuration)
What is "security"? Volvo tells you with its unique understanding and action
Lvs+keepalived high availability deployment practical application
太空游戏第12课: 盾牌
User and group and authority management
Space shooting Lesson 11: sound and music