Skip to content

Instantly share code, notes, and snippets.

@austinmao
Last active June 11, 2017 00:45
Show Gist options
  • Save austinmao/ee439b715f4fc1cc3398af4c6f34e18b to your computer and use it in GitHub Desktop.
Save austinmao/ee439b715f4fc1cc3398af4c6f34e18b to your computer and use it in GitHub Desktop.
Redux.NET with Unity
using UnityEngine;
using Redux;
public static class Move {
// actions must have a type and may include a payload
public class Action {
public class Move: IAction {
public Vector2 inputVelocity { get; set; }
public Transform playerTransform { get; set; } // curent transform
// public Vector3 moveDistance { get; set; } // movement from current transform
}
public class Stop: IAction {}
}
// reducers handle state changes
public static class Reducer {
public static State Reduce(State previousState, IAction action) {
if (action is Action.Move) {
return Move(previousState, (Action.Move)action);
}
return previousState;
}
public static State Move(State previousState, Action.Move action) {
var inputVelocity = action.inputVelocity;
var playerTransform = action.playerTransform;
var playerVelocity = (inputVelocity.x * playerTransform.right) + (inputVelocity.y * playerTransform.forward);
var moveDistance = playerVelocity * Time.fixedDeltaTime;
// calculate and store moveDistance in state
State newState = new State {
Move = {
moveDistance = moveDistance,
moving = true
}
};
return newState; }
}
using UnityEngine;
using UniRx;
using UniRx.Triggers;
public class PCMoveObserver : MonoBehaviour {
void Start() {
observeAndDispatchInput();
}
void observeAndDispatchInput() {
this.FixedUpdateAsObservable()
// get inputs by axis
.Select(_ => {
var x = Input.GetAxis("Horizontal");
var y = Input.GetAxis("Vertical");
return new Vector2(x, y).normalized;
})
// performance optimization: only dispatch if non-zero movement
.Where(v => v != Vector2.zero)
// dispatch inputVelocity and GameObject transform to move reducer
.Subscribe(inputVelocity => App.Store.Dispatch(new Move.Action.Move {
inputVelocity = inputVelocity,
playerTransform = transform
}))
// dispose of the observable if GameObject is disposed
.AddTo(this);
}
}
using UnityEngine;
public class State {
public MoveState Move { get; set; }
}
public class MoveState {
public bool moving { get; set; }
public Vector3 moveDistance { get; set; }
}
@leefernandes
Copy link

How'd you install Redux.NET? I've used nuget to install to the /Assets/Plugins directory, but unity complains "The type of namespace Redux could not be found".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment