Search Unity

How to set the enum in my Custom Class through a constructor

Discussion in 'Scripting' started by Max_Chaos, Jul 26, 2019.

  1. Max_Chaos

    Max_Chaos

    Joined:
    Dec 18, 2013
    Posts:
    12
    How do I set the enum for the Voxel class when the constructor is called?

    Assets\Scripts\TestArray.cs(25,13): error CS0118: 'TestArray.Voxel.types' is a type but is used like a variable

    Code (CSharp):
    1.     [System.Serializable]
    2.     public class Voxel
    3.     {
    4.         public Vector3 pos;
    5.         public enum types {Air, Start, End, Water, Lava, Stone, Obsedian};
    6.  
    7.         public Voxel(Vector3 _pos, int _type)
    8.         {
    9.             pos = _pos;
    10.             types = (types)_type;
    11.         }
    12.     }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    You need to create an instance of your enum:
    Code (CSharp):
    1.     [System.Serializable]
    2.     public class Voxel
    3.     {
    4.         public Vector3 pos;
    5.         public Types type;
    6.  
    7.         public Voxel(Vector3 _pos, Types _type)
    8.         {
    9.             pos = _pos;
    10.             type = _type;
    11.         }
    12.  
    13.         public enum Types {Air, Start, End, Water, Lava, Stone, Obsedian};
    14.     }
     
    Bunny83 likes this.
  3. Max_Chaos

    Max_Chaos

    Joined:
    Dec 18, 2013
    Posts:
    12
    Spot on, thanks Vryken, much appreciated!!!
     
  4. vycanis1801

    vycanis1801

    Joined:
    Feb 11, 2020
    Posts:
    12
    How can you do this and keep the enum private?
     
  5. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    You can't. The enum needs to be public in order for other classes to use it when setting values.
    What benefit would there be to make it private in this context anyway?
     
    Bunny83 likes this.