CS2335
Master_v2
Master_v2
  • Introduction
  • Introduction
    • Introduction
      • Design
      • Game Design
    • Unity - Download
    • Visual Studio - IDE
    • Hero's Journey
  • Unity Basics
    • Unity Editor Windows
    • MonoBehavior - Base-Class
    • Unity Engine - Event Functions
  • Getting Started
    • UI-Elements
    • Animator Controller
      • Animation Steps
    • PlayerController Flow Chart
    • PlayerController Code
      • PlayerController - V1 - S20
      • PlayerController V2 S20
      • PlayerController V3 S20
  • Project 1 - Simple Game
    • Overview
    • Project 1 - Get Started
      • UML Class Diagram
    • Player GameObject
      • PlayerController.cs V2
      • PlayerController.cs V3
    • Create 2D Sprite Prefab: Rock
    • Sorting Layers
  • Project1 Code
    • PickUp PreFabs
    • Player GameObject
    • PlayerController - jump
    • GameData Version1
    • PlayerStats Version1
    • MiniGameManager
      • Logic Diagram
    • Simple Spawner
    • Utility Class
  • Project1 Enhancements
    • PickUp - SelfDestruct
    • Spawn from List of Prefabs
  • Project 2 - StateManager
    • Project 2 - Learning Objectives
    • Project 2 - Starter Assets
    • Project 2
      • State Machine Framework
        • Singleton Pattern
      • StateManager - Singleton Design Pattern
      • IStateBase, BeginState
      • Project 2 -Steps: Create new Scene and State
      • Project 2 - List of Steps
        • Project 2 - Starter Code
  • Project 2 -Dialog
    • Hide_Show_Panel Script
    • Configure TitlePanel, DecisionPanel
    • Simple Dialog Prefab
    • Conversation Scriptable Objects
    • DialogManager_ConvList
    • Image Transitions for Buttons
  • UI Components
    • Finding Game Objects
    • Game Objects: UI vs. 2D Sprite
    • UI Elements
      • Canvas: Screen-Space Render-Mode
      • UI-Buttons To Change Scene
      • Text Input
  • Project2 Resources
    • Visual Novel in Unity-Links
    • Scriptable Object Factory
      • ScriptableObjects
    • Dialog Prefab Packages
  • Project 3 - Overview
    • Branching Story Structures
    • Dictionary Data-Structure
      • Unity PlayerPrefs Dictionary
    • Dictionary: User-Choice Data
      • User-Choices - Example
        • Dictionary Value to Disable Options
    • Simplified Mini-Game
      • PlayerController_v2 Mods
        • PlayerController_v2_final
      • MiniGameManager_v2
  • Proj3: Inventory System
    • Inventory-System
      • Install and Configure
      • Diagrams, Resources
        • Item, Gem, Potion Classes
        • Inventory Class
      • InventoryDisplay, Slot UI
        • InventoryDisplay Class
        • Slot Class
        • Hazard Class
        • Layout Groups
      • Customization Steps
        • Configure Animation
        • AddItem Button
        • Concrete Class: Food
        • MiniGame Mods
          • PlayerController Mods
      • Code: InventorySystem
        • GameData, PickUp Mods
      • Resources: Data Structures
  • Proj3: Custom UnityEvents
    • Event Publishing Patterns
    • Custom Event Messaging
  • Proj3: Mini-Game
    • MiniGame-Overview-Proj3
    • LevelManager
      • LevelManager Logic Diagram
      • LevelManager FSM
      • LoadLevel, StartLevel Logic
      • Code Framework
    • Timer
  • Project 3 - Code Mods
    • Project 3 - Steps
    • Project 3 - Code
      • Code: Final Versions
        • PlayerController Mods
          • PlayerController_v2 Mods
        • GameData - Final
        • LevelManager
        • PlayerStats - Final
        • PickUp, Hazard, ScorePickUp
        • Spawner - Final
        • CameraFollow
        • ScreenFader
        • MiniGameState
        • Example: EndState
      • MiniGameWin Logic
  • Optional, Supplemental Content
    • Optional Content
      • Adding Audio
      • Screen Fading and Reloading
      • ScriptableObjects
      • Disable Debug Logging
      • Events and Actions
      • Saving Data - Serialization
      • Parallax Scrolling
      • Change Sprites
  • C# Language
    • C# Language
      • Variables
      • Enum
      • Encapsulation
        • C# Properties
        • Access Modifiers
      • Inheritance
      • Polymorphism
      • Interface
      • Switch-Case
      • List< T >
      • Queue< T >
      • Dictionary
      • Foreach
      • Static
      • Ternary Operator: ?
      • this
      • Delegates
    • Diagrams
      • State Machine Framework
      • UML Class Diagrams
      • Level Manager Logic Diagram
      • Flow-Chart: NumberGame
      • FSM: NumberGame
    • Glossary
    • References and Resources
    • Random Thoughts
Powered by GitBook
On this page
  • IStateBase - Interface
  • IStateBase - Why do we need it?
  • Code: IStateBase
  • Code BeginState.cs

Was this helpful?

  1. Project 2 - StateManager
  2. Project 2

IStateBase, BeginState

IStateBase - Interface

IStateBase is a custom interface that we will have all StateX classes implement. This guarantees that all States will implement all Properties and Methods defined in this interface.

C# Interfaces in Unity

Interfaces provide a method to define a set of behaviors that we want to insure are implemented across several classes. We can only specify that any custom class can only have 1 parent class, in most of our Unity custom code, MonoBehaviour is that base-class. So, in order to implement related behavior across different classes, we'll use interfaces, since any class can implement any number of interfaces.

StateManager, will use an IStateBase object reference to keep track of the current active state instance. StateManager will execute the methods defined the interface IStateBase for the currently activeState. StateManager delegates responsibility to the current activeState using these methods.

IStateBase - Why do we need it?

Here is how we'll use IStateBase, we'll use it to refer to the currently active state, and this reference will be created and used in the StateManager instance as a way to keep track of the current state. With this reference to the activeState the StateManager can activate methods (execute functions) on the activeState, even though the states will be changing throughout the course of the game, across different scenes. This is how we remember where the player is during the game's execution. We could create a list to keep track of all of the states that the player has visited - we'd want to push some token which represents a state onto an ordered list - then these can be accessed as necessary from other objects.

Here's how we use it!

// in StateManager.cs

IStateBase activeState;  //

void Start(){
    activeState = new BeginState( );  //reference to first activeState
    curState = activeState.Scene;
}

Code: IStateBase

using UnityEngine;
using System.Collections;

///
///  
/// <summary>
/// I state base.  
/// Interface for all StateX.cs classes  
/// </summary>
public interface IStateBase
{

    /// <summary>
    /// Gets the scene number - enum
    /// </summary>
    /// <value>The scene.</value>
    GameScene Scene { // Inteface Property
        get;
    }

    //all interface methods are public by default!

    /// Similar to Unity Start()  
    /// exectued once, after scene is loaded - called from StateManager
    /// Used to initialize object references - can be used to cache object references
    /// </summary>
    void InitializeObjectRefs ();
}

StateX.cs

Each custom State class that implements IStateBase must implement the State Property and the 3 declared methods. This will allow StateManager to call these methods for each State instance when it becomes the current activeState.

Scene Logic and Event

Each State class definition contains code to control the scene's logic and event management. Below is the starter code for the BeginState class, this contains code that finds the EndScene Button GameObject, then creates an objectReference to the Button component. Then we define a function that we add as a Listener to the Button Component's onClick event. Finally, we must write the logic we want executed in our custom function which will cause the scene to change and which also instantiates the new State and make this connection with the StateManager because we're calling the StateManager SwitchState method at the same time that we're calling the constructor for the new State.

Code BeginState.cs

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement; //add to all State Files

//Spring 2020
public class BeginState : IStateBase
{

    /// <summary>
    /// The scene.
    /// </summary>
    private GameScene scene;

    /// <summary>
    /// Gets the scene number - enum
    /// </summary>
    /// <value>The scene.</value>
    public GameScene Scene
    {
        get { return scene; }
    }

    //GameScene objectRefs
    private Button optionBtn1, optionBtn2;

    /// <summary>
    /// Initializes a new instance of the <see cref="BeginState"/> class.
    /// </summary>
    public BeginState()
    {
        scene = GameScene.BeginScene; //make sure this matches Unity Scene Name
    }

    /// <summary>
    /// Similar to Unity Start() 
    /// exectued once, after scene is loaded - called from StateManager
    /// Used to initialize object references - can be used to cache object references
    /// </summary>
    public void InitializeObjectRefs()
    {
        optionBtn1= GameObject.Find("ButtonOption1").GetComponent<Button>();
        optionBtn1.onClick.AddListener(LoadEndScene);

        Debug.Log("Initialize Refs - BeginState");
    }

    /// <summary>
    /// Event handler - called when endBtn is clicked
    /// Loads the end scene.
    /// public method can be executed by button onClick event
    /// </summary>
    public void LoadEndScene()
    {
        Debug.Log("Leaving BeginScene going to EndScene");
        StateManager.instanceRef.SwitchState(GameScene.EndScene);  
    }
} //end class BeginState

PreviousStateManager - Singleton Design PatternNextProject 2 -Steps: Create new Scene and State

Last updated 5 years ago

Was this helpful?