1

I'm trying to create a function to generate a random object from a subset of objects, and from that contain a value from a subset of values.

Currently I'm using switch/case and it works, I was just curious if there was a better way.

Class containing main function:

public class Loot : MonoBehaviour, IPointerClickHandler {
    enum BaseType {Sword, Dagger};
    enum BaseQuality {Weak, Normal, Strong}

    public void OnPointerClick(PointerEventData eventData) {
        Array baseTypes = Enum.GetValues(typeof(BaseType));
        Array baseQualities = Enum.GetValues(typeof(BaseQuality));

        System.Random random = new System.Random();

        String baseType = baseTypes.GetValue(random.Next(baseTypes.Length)).ToString();
        String baseQuality = baseQualities.GetValue(random.Next(baseQualities.Length)).ToString();

        int damage = 0;
        switch(baseQuality) {
            case "Weak":
                damage = -1;
                break;
            case "Strong":
                damage = 1;
                break;
        }

        Weapon weapon = new Weapon();
        switch(baseType) {
            case "Sword":
                weapon = new Sword();
                break;
            case "Dagger":
                weapon = new Dagger();
                break;
        }

        weapon.Name = baseQuality + " " + baseType;
        weapon.Attack += damage;

        Debug.Log("created " + weapon.Name + " with attack " + weapon.Attack);
    }
}

Weapon class:

public class Weapon : Item {
    public int Attack { get; set; }
}

Sword class (Dagger class is essentially the same):

public class Sword : Weapon {
    public Sword() {
        Attack += 3;
    }
}

This is working as is, but I was curious if there's a more dynamic way to do this for when I implement more weapon types and qualities.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Workey
  • 21
  • 2
  • 2
    I would suggest having a read through this post: https://stackoverflow.com/q/2706500/74757. You're newing up a `System.Random()` on each click, but should be reusing a single instance of it. You're also doing a coin-flip approach here, so you'd have to rethink a bit if you want to make certain weapons have a higher probability of being created. – Cᴏʀʏ Dec 30 '18 at 15:15

2 Answers2

0

I would make the Random variable a global variable. But I don't think that it can get more dynamic. So yes just put that System.Random random = new System.Random(); above the method and you should be fine. (You are generating a new random object every time you enter that method, but it should be fine if you just generate it one time) I hope I could help, have a nice day.

Samuel
  • 13
  • 3
0

If you have constructors without parameters you can use reflection this approach will have shorter code

 Type[] weaponTypes= new Type[] { typeof(Sword), typeof(Dagger) };
 Weapon weaponInstance = (Weapon)Activator.CreateInstance(types[baseType]);
Serg Shevchenko
  • 662
  • 1
  • 5
  • 21