导入 UniRx 报错
版本:UniRx - Reactive Extensions for Unity / Ver 6.2.2
Assets\Plugins\UniRx\Scripts\InternalUtil\CancellableTaskCompletionSource.cs(17,57): error CS0433: The type 'TaskCompletionSource<TResult>' exists in both 'System.Threading, Version=1.0.2856.102, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Assets\Plugins\UniRx\Examples\Sample02_ObservableTriggers.cs(2,13): error CS0234: The type or namespace name 'Triggers' does not exist in the namespace 'UniRx' (are you missing an assembly reference?)
因为UniRx不支持.net 4.0,
只支持
Scripting Runtime Version == .Net 3.5 Equivalent(Deprecated)
Api Compatibility Level == .NET 2.0 Subset
所以按以下操作改
1 . File -> Build Settings -> Player Setting -> Scripting Runtime Version = .Net 3.5 Equivalent(Deprecated)
2 . 在重新导入UniRx
值监听
//值监听
void Start()
{
//变量值改变时发生订阅事件
ReactiveProperty<long> CurrentHp = new ReactiveProperty<long>(1000l);
ReactiveProperty<bool> isDead = new ReactiveProperty<bool>((CurrentHp.Value <= 0));
CurrentHp.Subscribe(_ =>
{
isDead.Value = (CurrentHp.Value <= 0);
Debug.Log("CurrentHp:" + CurrentHp.Value + " 的值发生变化,输出本文字");
}
);
isDead.Subscribe( _ => Debug.Log("isDead:" + isDead.Value + " 的值发生变化,输出本文字"));
//每按一次鼠标左键,更新值
Observable.EveryUpdate()
.Where(_ => Input.GetMouseButtonDown(0))
.Subscribe(_ =>
{
CurrentHp.Value -= 99l;
});
}
计时器
//执行一次,倒计时
Observable.Timer(TimeSpan.FromSeconds(10f))
.Subscribe(_ =>
{
Debug.Log("倒计时:10秒钟后输出当前文字。");
});
//循环执行,间隔指定时间
Observable.Interval(TimeSpan.FromSeconds(0.7f))
.Subscribe(_ =>
{
Debug.Log("每间隔:0.7秒输出当前文字。");
});
//条件循环执行,间隔指定时间,当isComplete=false一直循环检测isComplete的值,直到=true 执行Subscribe()然后跳出循环.
bool isComplete=false;
IDisposable attack1 = Observable.Interval(TimeSpan.FromSeconds(0.7f))
.First(_ => isComplete) //First就是获取第1个通过的事件.如果你只想条件只执行一次,
.Subscribe(_ =>
{//当前函数只执行一遍.
Debug.Log("每间隔:0.7秒循环检测isComplete的值,直到isComplete等于true时输出当前文字,然后就停止循环");
});
//手动控制,强制停止//如果当前还在执行的话,销毁,用于当GameObject循环停止脚本的循环
if(attack1!=null)attack1.Dispose();
条件
Observable.EveryUpdate()
.SkipWhile(条件) //.SkipWhile(_ => true)
除非一开始条件就是 true,则循环,不执行Subscribe()
除上面情况外,则循环,执行Subscribe()
.Where(条件)
如果指定的条件为 true,则循环,执行Subscribe()
如果指定的条件为 false 则循环,不执行Subscribe()
.TakeWhile(条件)
如果指定的条件为 true,则循环,执行Subscribe()
如果指定的条件为 false 则停止循环,不执行Subscribe()
.First(条件)
如果指定的条件为 false 则循环,不执行Subscribe()
如果指定的条件为 true,执行Subscribe(),然后停止循环
.Subscribe(_ =>{});
.First
有两种作用:
1是执行一次,
.First(_ => bool)
2.取第一个
.First()
生命周期
gameObject生命周期销毁 让UniRx的循环随着gameObject销毁而停止循环
.TakeWhile(this) .TakeUntil(this) .TakeUntilDisable(this) .TakeUntilDestroy(this) .RepeatUntilDestroy(this) .RepeatUntilDisable(gameObject/component) .AddTo(gameObject)促进流的自动释放 var Subject = Observable.IntervalFrame(30) .TakeUntilDisable(this) .Subscribe(x => Debug.Log(x), () => Debug.Log("completed!")); Subject.AddTo(gameObject);