当前位置:网站首页>Introduction summary of using unirx in unity
Introduction summary of using unirx in unity
2022-07-25 05:30:00 【A programmer who is not for whom_】
UniRx Introduction summary
What is? UniRx?
UniRx Namely Unity Version of Reactive Extensions,Reactive Extensions Chinese meaning : Reactive expansion , Responsive refers to the observer and timer , Extension means LINQ The operator of .Reactive Extensions To be good at dealing with asynchronous logic in time 、 And minimalist API Style comes from admiration .
Why use UniRx?
Because many logical operations on the project need to be processed asynchronously in time , Therefore, there are often many asynchronous logics that need to be implemented . This is also why there is the concept of Ctrip .
In the project , Like the playback of animation 、 Network request 、 Resource loading 、 Scenario transition and so on are the logic of asynchronous operation in time , When we implement the above function modules on the project , It is often implemented through a large number of callbacks , It may cause the project to be filled with a large number of callbacks to handle some logic , The relatively better method is practical messages / Events are implemented , But the result may also lead to a large number of events in the project , After a period of time, you may not understand the logic you write .
and UniRx The emergence of just solved this problem , It's between callbacks and events .
- It has the concept of events , But its events are like flowing water , We need to organize these events in the development process 、 Transformation 、 Filter 、 Merge and so on
- It also uses callbacks , But its callback is after the event is organized , You only need to call once to handle the event
Commonly used API
Timing function
In normal projects, you may often encounter some logical operations triggered after a period of time
Usually, it is possible to use Synergetics
void Start()
{
StartCoroutine(Timer(10, DoSomething));
}
IEnumerator Timer(float seconds,Action callback)
{
yield return new WaitForSeconds(seconds);
callback();
}
void DoSomething()
{
Debug.Log("TODO");
}
The code declaration implements the same function as above , after 10s To print , Is the code clear .
void Start()
{
Observable
.Timer(TimeSpan.FromSeconds(10))
.Subscribe(e => {
Debug.Log("DoSomething");
});
}
Another thing to note is that the above writing is not consistent with Unity Medium MonoBehaviour Life cycle binding , Probably MonoBehaviour After destruction , The logic is still executing , May cause null pointers . You need to add... At the end .AddTo(this), When the life cycle is destroyed , The script logic will also be destroyed . This is what we need to pay attention to when writing logic .
The code is as follows
void Start()
{
Observable
.Timer(TimeSpan.FromSeconds(10))
.Subscribe(e => {
Debug.Log("DoSomething");
})
.AddTo(this);
}
Update
When writing a function module, it may be in Update Some logic is defined in , As the project may Update There is a lot of code in . Use UniRx Can make the code independent of each other . As shown below :( Be careful not to forget to add .AddTo(this))
void Start()
{
Observable
.EveryUpdate()
.Subscribe(e => {
Debug.Log("QQQ");
})
.AddTo(this);
Observable
.EveryUpdate()
.Subscribe(e => {
Debug.Log("WWW");
})
.AddTo(this);
Observable
.EveryUpdate()
.Subscribe(e => {
Debug.Log("EEE");
})
.AddTo(this);
}
The above code can be defined separately in the actual project through the division of business modules , It is also convenient for future maintenance .
The operator First
You may also encounter related functions that need to be performed for the first time but do not need to be performed later in your project , We may define a bool value , Assign a value of false, Take the first mouse click as an example , Keywords are First. The code is as follows
void Start()
{
Observable
.EveryUpdate()
.First(_=>Input.GetMouseButtonDown(0))
.Subscribe(e => {
Debug.Log("EEE");
})
.AddTo(this);
}
The operator Where
This Where It can be understood that it can be executed only when certain conditions are met . The code is as follows , Print out when the left mouse button is pressed .
void Start()
{
Observable
.EveryUpdate()
.Where(_ => Input.GetMouseButtonDown(0))
.Subscribe( _=>
{
Debug.Log("DOSomething");
})
.AddTo(this);
}
ReactiveProperty
ReactiveProperty It means responsive property , As the name suggests, when assigning a value to an attribute in the project, the relevant logic will be executed dynamically , Go straight to the code , What are the limitations of the following code , When the value changes , The corresponding method response can only be performed inside the attribute , What if I want to call it externally ? You may need to define a delegate to bind .UniRx There's a simpler API;
Conventional writing
private int age;
public int Age
{
get
{
return age;
}
set {
if (value>0)
{
age = value;
OnAgeChanged();
}
}
}
void OnAgeChanged()
{
}
UniRx usage
public ReactiveProperty<int> Age = new ReactiveProperty<int>();
void Start()
{
Age.Subscribe(age =>
{
Debug.Log(" Method changed after assignment ");
});
Age.Value = 22;
}
Yes UGUI Support for
have access to UniRx Yes UI Control for dynamic binding , Other usages can be queried by yourself . You can also add Where、First Wait for the operator .
public Button btn;
public Toggle toggle;
void Start()
{
btn.OnClickAsObservable()
.Subscribe(_ =>
{
Debug.Log("BtnClick");
});
toggle.OnValueChangedAsObservable()
.Subscribe(isOn =>
{
if (isOn)
{
}
else
{
}
});
}
The operator Merge
What is introduced here is right UniRx The defined flow logic performs the merge operation , The code is as follows : The code defines two event flows respectively , By the operator Merge A merger , When the left or right mouse button is pressed , Will print out .
void Start()
{
// Define the flow 1
var stream01 = Observable
.EveryUpdate()
.Where(_ => Input.GetMouseButtonDown(0));
// Define the flow 2
var stream02 = Observable
.EveryUpdate()
.Where(_ => Input.GetMouseButtonDown(1));
Observable.Merge(stream01, stream02)
.Subscribe(_ => {
Debug.Log("DoSomeThing");
})
.AddTo(this);
}
That's all for the basic usage .
边栏推荐
- School day (summer vacation daily question 2)
- VPP不能加载UP状态接口
- C Programming -- the solution of dynamic programming of "the sum of the largest subarray"
- Pikachu vulnerability platform exercise
- Execution process of NPM run XX
- Introduction to base ring tree
- 项目管理工具——项目开发者工具
- Deep error
- Build keyword driven automated testing framework
- In depth understanding of pre post + +, -- and negative modulus
猜你喜欢
[email protected] R & D effectiveness measurement indicators"/>Learning records [email protected] R & D effectiveness measurement indicators

Easyrecovery free data recovery tool is easy to operate and restore data with one click

聊聊 Redis 是如何进行请求处理

项目管理工具——项目开发者工具

Introduction to kubernetes

Execution process of NPM run XX

Implementation principle of epoll

微服务 - 网关Gateway组件

Implement is by yourself_ convertible

How to carry out the function test with simple appearance and complex interior?
随机推荐
VPP cannot load up status interface
弹性布局总结
JS common code questions array de duplication - Custom New throttling and anti shake - deep copy - instanceof URL parameter extraction - thousand separator - array to tree structure - array flattening
深圳随到随考,科目四随到随考,科三理论第二理论随到随考说明
JWT(json web token)
Deep error
Uniapp custom application exit execution content
The difference between $write and $display in SystemVerilog
LCP plug-in creates peer-to-peer 802.1ad interface
批量下载视频小技巧
STL notes (II): template and operator overloading
Openfegin remote call lost request header problem
Which side of Nacos has the SQL script of this column?
微服务 - 配置中心 - Nacos
Necessary skills for mobile terminal test: ADB command and packet capturing
50:第五章:开发admin管理服务:3:开发【查询admin用户名是否已存在,接口】;(这个接口需要登录时才能调用;所以我们编写了拦截器,让其拦截请求,判断用户是否是登录状态;)
STL notes (VI): container vector
Event cycle mechanism browser nodejs async await execution sequence promise execution sequence interview questions
Implement is by yourself_ convertible
Render Optimization: repaint and reflow