SOCs for Unity

by Sam Fereday

JavaScript

/// Conditional states idea for Unity and scriptable objects
// State - only ever exists here (see the principles for this on Redux - single point of state).
// This would be your scriptable object or repo, etc. In my instance I'll be using SO's. The contract you see here must be met at all times for SO's to be confidently used. Anything different and the idea kind of breaks down.
const stateObj = {
  fullfilled: false,
  setState: (mode) => {
    this.fullfilled = mode;
  },
  getState: () => {
    return this.fullfilled;
  }
}

/// A simple test to show how the flow might work with the State-Activation-Action idea.
// Activation
const activator = ({
  setState
}) => {
  console.log("Activator fired.");
  setState(true);
}

// Action
const action = ({
  getState
}) => {
  if (getState()) {
    console.log("Action has fired.");
  } else {
    console.log("Action is silent.");
  }
}

// Fire action in initial state, nothing happens.
action(stateObj);

// Activator has internal logic that'll be resolved under various circumstances.
activator(stateObj);

// Fire action again after activator has run.
action(stateObj);

/// How might this look in Unity?
// Puzzle script attaches to any entity that will 'activate' a state mode depending on its own internal logic. Could involve solving a puzzle, picking up an item, talking to someone, etc.
const puzzle = {
  scriptableObject: stateObj,
  onPuzzleAttempt: (userInput) => {
    const playerAnswer = 1 + userInput === 2;
    const {
      setState
    } = this.scriptableObject;
    setState(playerAnswer);
  }
}

// Actions are only really fired when interacted with, or, told from a remote location to do so. They won't do anything if the state given is falsey. Again actions just attach to anything that require them to do so (doors, bridges, you name it).
const door = {
  scriptableObject: stateObj,
  onInteracted: () => {
    const {
      getState
    } = this.scriptableObject;
    if (getState()) {
      console.log("Played...