basically Im following a tutorial to create this “state machine” as described in the eBook “Learning C# By Developing Games In Unity 3D”
Anyway, I’m supposed to have a code that works by whenever I press SPACE it should shift state as well as printing out in the console what state it is in. Like this:
(So here SPACE has been pressed 3 times I think, this is from the book)
This is when I write the code, nothing happens when I press space… Earlier it would switch 1 state and that was it, not it just writes begin-state twice, and I don’t know what I’ve written wrong… My code looks almost identical to the book and I simply can’t pinpoint the mistake, I have 6 scripts, but 2 of them are almost exactly identical to another but just for different states, so I’ll just show those where I think the mistake might be in:
4 Samples of my code
-
StateManager
-
IStateBase
-
BeginState
-
PlayState
using UnityEngine;
using System.Collections;
using Assets.Code.States;
using Assets.Code.Interfaces;
public class StateManager : MonoBehaviour
{
private IStateBase activeState;
void Start ()
{
activeState = new BeginState(this);
}
// Update is called once per frame
void Update ()
{
if (activeState != null)
{
activeState.StateUpdate();
}
}
public void SwitchState(IStateBase newState)
{
activeState = newState;
}
}
using UnityEngine;
using System.Collections;
namespace Assets.Code.Interfaces
{
public interface IStateBase
{
void StateUpdate();
void ShowIt();
void StateFixedUpdate();
}
}
using UnityEngine;
using System.Collections.Generic;
using Assets.Code.Interfaces;
namespace Assets.Code.States
{
public class BeginState : IStateBase
{
private StateManager manager;
public BeginState(StateManager managerRef)
/*Constructer*/
{
manager = managerRef;
Debug.Log ("Constructing BeginState");
}
public void StateUpdate()
{
if(Input.GetKeyUp(KeyCode.Space))
{
manager.SwitchState(new BeginState(manager));
}
}
public void ShowIt()
{
}
public void StateFixedUpdate()
{
}
}
}
using UnityEngine;
using System.Collections.Generic;
using Assets.Code.Interfaces;
namespace Assets.Code.States
{
public class PlayState : IStateBase
{
private StateManager manager;
public PlayState(StateManager managerRef)
/*Constructer!*/
{
manager = managerRef;
Debug.Log ("Constructing PlayState");
}
public void StateUpdate()
{
if(Input.GetKeyUp(KeyCode.Space))
{
manager.SwitchState(new PlayState(manager));
}
}
public void ShowIt()
{
}
public void StateFixedUpdate()
{
}
}
}