Skip to content

Instantly share code, notes, and snippets.

@Protonz
Last active October 23, 2017 08:28
Show Gist options
  • Save Protonz/167af7c6c571864e6208fb37f3bd14d1 to your computer and use it in GitHub Desktop.
Save Protonz/167af7c6c571864e6208fb37f3bd14d1 to your computer and use it in GitHub Desktop.
Testing Out a Simple Component Manager
using UnityEngine;
using UniRx;
using UnityEngine.SceneManagement;
public class Character {
public enum State {
Idle,
Attacking
}
public ReactiveProperty<State> CurStateObservable = new ReactiveProperty<State>();
public string Name;
public Character( string name ) {
Name = name;
}
}
public class RxCharacter : MonoBehaviour {
ReactiveCollection<Character> CharacterManager = new ReactiveCollection<Character>();
private void CharacterAdded( Character character ) {
CharacterManager.Add(character);
}
public IObservable<Character> NewAndExistingCharacters {
get {
IObservable<Character> existingCharacters = CharacterManager.ToObservable();
IObservable<Character> newCharacters = CharacterManager.ObserveAdd()
.Select(e => e.Value);
return existingCharacters.Merge(newCharacters);
}
}
public IObservable<string> CharacterStateStream {
get {
return NewAndExistingCharacters
.SelectMany( character => character.CurStateObservable
.Select( newState => string.Format("{0} {1}", character.Name, newState) ) );
}
}
/*
Expected Output:
c1 Idle
c2 Idle
c1 Attacking
c3 Attacking
*/
private void Start() {
Character c1 = new Character("c1");
Character c2 = new Character("c2");
CharacterAdded(c1);
CharacterStateStream
.Subscribe(state =>
Debug.Log(state)
).AddTo(this);
CharacterAdded(c2);
c1.CurStateObservable.Value = Character.State.Attacking;
Character c3 = new Character("c3");
c3.CurStateObservable.Value = Character.State.Attacking;
CharacterAdded(c3);
Observable.EveryUpdate()
.Where(_ => Input.GetKeyDown(KeyCode.R))
.Subscribe(_ =>
SceneManager.LoadScene(0)
).AddTo(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment