WeightedOptions provides functionality to create Lists of weighted objects to randomly pick from, with uneven chances for each object. Objects with a higher weight value have more chance of being selected than those of a lower weight. This is mainly useful in gameplay code generating environment, obstacles or enemies.
Within DuskModules, WeightedOptions is usually only used by addon folders.
WeightedOptions has no dependencies.
Any object can be a WeightedObject by implementing the IWeightedOption interface. This interface requires two methods:
bool IsAnOption(object caller); which returns true or false whether this option is currently available for choice by the caller object.
float GetWeight(); which returns the current weight of the object.
It's recommended to extend the WeightedOption serializable class instead, which already provides such features, and allows extension of them by overriding the methods.
Any List of IWeightedOption items has two extension methods, allowing you to easily get random options from the List:
List<T>.GetWeightedRandom(object caller = null); which gets and returns a single randomly picked object from the list.
List<T>.GetWeightedRandomCount(object caller = null); which gets the amount of available options to pick from. Useful to detect whether the list has at least one available option.
public class MyBehaviour : MonoBehaviour {
[System.Serializable]
public class Item : WeightedOption {
public string name;
public float value;
}
public List<Item> items;
void Awake() {
Item item = items.GetWeightedRandom();
}
}
Don't forget to add using DuskModules.WeightedOptions; to any script using the module.