- Home /
(C#) How to access enum from a remote object?
Hey guys I was wondering how I might be able to access a remote enum in C#. Right now i have this enum setup in a kinda global "meta" object. I was planning on using this as a sort of index for my layers.
public enum Layers { playerActorLayer = 8, civilianActorLayer = 9, enemyActorLayer = 10, };
Now I try and grab this in the awake function of my other script as follows
myLayers = GameObject.Find("debug_terrain").GetComponentInChildren<enumLayers>();
Which should grab the script component with the public enum from the child object it's living in on my terrain. However I can't seem to access myLayers.Layers in the other scirpt. Am I not handling this the right way? I have the enum scroped public. Is there something specific to enums that I am missing?
Answer by whydoidoit · Jul 07, 2012 at 10:24 AM
The enum is a global static thing scoped by the class it belongs to so it looks like you should be accessing it like this:
enumLayers.Layers
Does this mean that I do not need to instantiate an object in order to access the enum? I can just call it from any other script in the scene kinda as follows?
case enumLayers.Layers.playerActorLayer :
???
Is an enum always considered to be static even if not implicitly cast as such?
The definition of an Enum is always static yes - obviously you would need an instance to find a variable of that enum that was attached to a class.
So in your example in the comment you would find that the switch in which the case you write exists needs to access a variable, but the case statement will just use the definition as you write it.
I don't entirely understand why I would need to get the enum in a variable outside of the "body" of the switch statement but am able to access it via it's definition inside the switch (for example in that case line there).
Thanks so much for all the help!
Answer by nventimiglia · Jul 08, 2012 at 01:44 AM
All an Enum is a glorified int. I believe you fundamentally misunderstand it.
public enum NumberEnum{
One = 1,
Two = 2,
Joker= 3,
}
void Awake(){
var one = 1;
var two = 2;
var three = 3;
if(one == (int)NumerEnum.One)
Debug.Log("One");
if(two == (int)NumerEnum.Two)
Debug.Log("Two");
if(three== (int)NumerEnum.Joker)
Debug.Log("Joker");
}
Your answer
Follow this Question
Related Questions
How do I call an enum from another script? 3 Answers
Accessing Enumeration from another script issue 1 Answer
error BCE0022: Cannot convert error, please help 3 Answers
Neater way to test an Enum in a different script? 1 Answer
access enum values 0 Answers