- Home /
Changing enum values
Hello! I currently have a system set up where I use an enum called WeaponType that has the values Sword, Greatsword, Lance, Fists. I want to be able to change these weapons with a button press depending on whether some conditions are true. To do this, I created an int data type that gets the values of the enum. Like this,
private int numberOfWeaponTypes = System.Enum.GetValues(typeof(WeaponType)).Length;
I have a function set up to switch between weapon types, which everything is working just fine right now. However, eventually, I want to be able to give the player the option to rearrange their weapon order, as I do not want Sword, Greatsword, Lance, Fists to be the order for the whole game. How would I go about doing this?
I appreciate any insight!
Answer by Dragate · Jul 19, 2019 at 06:49 AM
System.Array weaponTypes;
void Start(){
weaponTypes = System.Enum.GetValues (typeof(WeaponType));
SwitchOrder (0, 1, weaponTypes); //Switch 1st weapon with 2nd
}
void SwitchOrder(int a, int b, System.Array values){
var temp = values.GetValue (b);
values.SetValue (values.GetValue (a), b);
values.SetValue (temp, a);
}
Thank you for replying! I want to understand what is going on in this code. By putting "System.Array" in front of the weaponTypes variable (which should be an enum), will that do some kind of casting to an array?
Enum.GetValues() returns an array of the values of the constants in a specified enumeration. So if your enum is:
public enum WeaponType{
Sword,
Greatsword,
Lance,
Fists
}
weaponTypes will be of type WeaponType[] with 4 elements (each being a different WeaponType).
Oh! I see. Thank you for explaining that. I actually did not realize that Enum.GetValues() returns an array. I will try this out when I get a moment. I appreciate it, Dragate!
Your answer
Follow this Question
Related Questions
Problems with enums and switches (C#) 2 Answers
Cycling through enum with key press 1 Answer
Problem with my weapons switch statement C# 3 Answers
Switching Weapons (C#) 2 Answers