So I keep running into an interesting annoyance that I haven't bothered to solve, and I really should. The problem is weighted randomness. This comes in with enemies dropping pick-ups when they die or selecting ground sections in world generation. I want to be able to have some things appear more than others, but not limit the number of times something can appear.
For example, if I have 5 items (A, B, C, D, E) with weights (1, 5, 5, 2, 3, for a total of 16) I would want item A to appear 1/16 of the time. The most direct way (and likely most memory intensive way to do this is to fill in an array with multiple objects corresponding to their weight (A, B, B, B, B, B, C, C, C...); then pick which one to pull with a random generator.
There must be a better way, and I feel I should spend time to figure it out.
The way to do this using curves is pretty neat. You make an AnimationCurve that you can edit in the editor and in code use "AnimationCurve.Evaluate(float num)". That number is your x value on the curve and the associated y value is the result.
Here is my code to translate a 0.0-1.0 by 0.0-1.0 curve into a position in a list: int curveVal = Mathf.RoundToInt((plants.Count - 1) * plantWeightCurve.Evaluate(Random.value)); GameObject plant = plants[curveVal];
With the curve attached and a list of 20 objects you have a 50% chance of getting one of the first 5 in your list.
Again, this is neat...not so sure how useful it is to me. I feel like with this system I'll be spending a lot of time tweaking curves and getting unintended results. If I want a 50% chance to get object 1, a 20% chance to get objects 2 through 8, and 30% chance to get an object 9 through 20 my curve could turn out really bad looking. Going to keep testing different ideas.
Thinking about it more, a potential use for this type of weighting is not individual values, but value ranges. For example if I organize my ocean floor sections by surface incline I could then have a single list of ground sections and use different curves for the different ocean zones.
Continental shelf's curve would look like a very extreme exponential curve favoring the low incline sections. The continental slope's curve would be an extreme S-curve, and the abyssal floor would have a ceiling to prevent using any section with a curve.