Unity/UniRx/TMPro
提供: 初心者エンジニアの簡易メモ
TMP_DropDownサンプル
ObserveEveryValueChangedを使う場合
using UnityEngine; using UnityEngine.UI; using UniRx; using TMPro; public class SampleScene : MonoBehaviour { void Start() { TextMeshProUGUI tmpText = GameObject.Find("Text (TMP)").GetComponent<TextMeshProUGUI>(); TMP_Dropdown tmpDropdown = GameObject.Find("TmpDropdown").GetComponent<TMP_Dropdown>(); tmpDropdown.ObserveEveryValueChanged(_ => _.value) .Subscribe(index => { var value = dropdown.options[index].text; tmpText.text = value; }) .AddTo(gameObject); } }
AsObservableを使う場合
using UnityEngine; using UnityEngine.UI; using UniRx; using TMPro; public class SampleScene : MonoBehaviour { void Start() { TMP_Dropdown tmpDropdown = GameObject.Find("TmpDropdown").GetComponent<TMP_Dropdown>(); tmpDropdown.onValueChanged.AsObservable() .Subscribe(index => { var value = dropdown.options[index].text; tmpText.text = value; }) .AddTo(gameObject); } }
OnValueChangedAsObservableを作る形式。別途、下にあるようにUnityUIComponentExtensions.csに、OnValueChangedAsObservableを作る
using UnityEngine; using UnityEngine.UI; using UniRx; using TMPro; public class SampleScene : MonoBehaviour { void Start() { TextMeshProUGUI tmpText = GameObject.Find("Text (TMP)").GetComponent<TextMeshProUGUI>(); TMP_Dropdown tmpDropdown = GameObject.Find("TmpDropdown").GetComponent<TMP_Dropdown>(); tmpDropdown.OnValueChangedAsObservable() .Subscribe(index => { var value = dropdown.options[index].text; tmpText.text = value; }) .AddTo(gameObject); } }
UnityUIComponentExtensions.csへusing TMPro;が追加できない問題
別途、アプリ側のScriptディレクトリに、UnityUIExtensionsを作れば良い。
UnityUIExtensions.cs
sing System; using TMPro; namespace UniRx { public static class UnityUIExtensions { public static IDisposable SubscribeToText(this IObservable<string> source, TextMeshProUGUI text) { return source.SubscribeWithState(text, (x, t) => t.text = x); } public static IDisposable SubscribeToText<T>(this IObservable<T> source, TextMeshProUGUI text) { return source.SubscribeWithState(text, (x, t) => t.text = x.ToString()); } #if UNITY_5_3_OR_NEWER public static IObservable<int> OnValueChangedAsObservable(this TMP_Dropdown dropdown) { return Observable.CreateWithState<int, TMP_Dropdown>(dropdown, (d, observer) => { observer.OnNext(d.value); return d.onValueChanged.AsObservable().Subscribe(observer); }); } #endif } }
参考:https://github.com/neuecc/UniRx/issues/352
InputFieldPro
TMP_InputField tmpInputField = GameObject.Find("InputField (TMP)").GetComponent<TMP_InputField>(); // 入力してフォーカスを外したら tmpInputField.onEndEdit.AsObservable().Subscribe(value => { Debug.Log("value=" + value); tmpInputField.text = value; });