Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Singleton with Enum

Discussion in 'Scripting' started by martur94, Dec 23, 2015.

  1. martur94

    martur94

    Joined:
    Dec 22, 2015
    Posts:
    17
    How can i instantiate a enum for a machine state using singleton ?

    This is my code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GameSystem : MonoBehaviour {
    5.  
    6. private static GameSystem instance;
    7.  
    8. private GameSystem() { }
    9.  
    10.    public static GameSystem GetInstance
    11.    {
    12.       get
    13.       {
    14.          if (instance == null)
    15.          {
    16.              instance = new GameSystem();
    17.          }
    18.          return instance;
    19.       }
    20.    }
    21.  
    22.    public enum move
    23.    {
    24.        move_on,
    25.        move_off
    26.    }
    27. }
    28.  
    and i can not instantiate the enum
     
  2. kietus

    kietus

    Joined:
    Jun 4, 2013
    Posts:
    54
    Hello,

    I'm not sure about your issue, you don't need to instantiate the enum class. You may need an object to store the enum value. Like
    Code (csharp):
    1.  
    2. public move currentMove;
    3. // so u can do a
    4. currentMove = GameSystem.move.move_off;
    5.  
     
    Polymorphik likes this.
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    That's also not a state machine. The whole point of a state machine implementation is to avoid the use of enums :) (well, one of the points anyway...)
     
  4. martur94

    martur94

    Joined:
    Dec 22, 2015
    Posts:
    17
    More the enum does not fit for manipule a state machine ?
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Generally, the goal is to avoid huge if-else or switch statements. They're impossible to read and maintain and it makes it very difficult to add new states or variations of states. In managed languages (like C#) it makes sense to have each state be its own class (unmanaged languages will sometimes have each state be a singleton so that the programmer doesn't have to worry about disposal - with the downside being that the owner of the state has to carry around some statefulness on its own).