mercredi 31 mars 2021

create new object from enum number c#

I have made a enum type (MonsterTypes) with 4 types (Monster1, Monster2 , Monster3, Monster4) which should be possible to extend with more monsters. I want to chose a random type, and create an instances of a random monster, and rather than having if states stating if (System.Random.Next(4) = 1) Monster1.CreateMonster(Image)} which works. In order to automatically extend the random from 4-5 when a new enum is added.
var squadrons = MonsterTypes.GetNames( typeof( Squadron.SquadronType)).Length; in order to get the number of enums.
I encounter a problem when i try to initiate CreateMonster() without an if statement. If i use: ((MonsterTypes) System.Random.Next(4)).CreateMonster(Image) i get the error: "'MonstersTypes' does not contain a definition for 'CreateMonster' and no accessible extension method 'CreateMonster' accepting a first argument of type 'MonsterTypes' could be found (are you missing a using directive or assembly refrence?)

public static  class CreateNextMonster {
    public static IMonster ActiveMonster {get;private set;}
    private static System.Random rand = new System.Random();
    public static void CreateNewMonster (Img MonsterPicture) {
        var monstersTotal = Squadron.SquadronType.GetNames(typeof(Squadron.SquadronType)).Length;
        int nextMonster= rand.Next(monstersTotal);
        ((Monsters) nextMonster).CreateMonster();
    }
}



Aucun commentaire:

Enregistrer un commentaire