導入 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);