- Home /
Generating a word out of an array, each has its own rarity.
I'm making a script to generate random weapons with prefixes and a suffix. I've made 2 structs, one called ModifierPrefix and another called ModifierSuffix. They each have:
A name (string)
A damage modifier (float)
and a rarity (float between 1 and 10)
I just need a way to generate a random prefix and suffix based on it's rarity.
Here's the script:
using UnityEngine;
using System.Collections;
public class Weapons : MonoBehaviour {
[System.Serializable]
public struct ModifierPrefix {
public string modifier;
public float damageChange;
public float rarity;
}
[System.Serializable]
public struct ModifierSuffix {
public string modifier;
public float damageChange;
public float rarity;
}
[System.Serializable]
public struct Weapon {
public string name;
public float damage;
public ModifierPrefix[] prefixes;
public ModifierSuffix suffix;
}
public Weapon[] weapons;
public ModifierPrefix[] possiblePrefixes;
public ModifierSuffix[] possibleSuffixes;
// Generate a new weapon
}
Answer by DeeCeptor · Aug 17, 2015 at 10:34 PM
A simple way to do it would be to create a large array of prefixes and have it filled up with prefixes based on their rarity, and then selecting a random prefix from this list.
From these suffixes: [name, rarity], [deadly, 1], [rare, 3], [common, 6]
you would generate a list looking like: (deadly, rare, rare, rare, common, common, common, common, common, common)
The rarity dictates how many copies of each prefix you put into this array. Now this array represents your chances of getting each prefix.
Now use Mathf.Range(0, listSize - 1)
to select a prefix from it.
Rinse and repeat for suffixes and damage.
I'm just doing it, but i just realised - what if i wanted a decimal number for the rarity? EDIT: Also, how do i append something to an array?
Answer by cjdev · Aug 18, 2015 at 10:13 PM
Personally I would change the Arrays to Lists and use LINQ to sort through them by rarity. You could do something like this:
using System.Collections.Generic;
using System.Linq;
public List<ModifierPrefix> possiblePrefixes;
//Gets a collection of modifiers that have a rarity > 7.0
IEnumerable<ModifierPrefix> sorted = possiblePrefixes.Where(x => x.rarity > 7.0f);
//Picks a modifier from a random location in the collection
ModifierPrefix randomPrefix = sorted.ElementAt(Random.Range(0, sorted.Count()));
I'm relatively new to C#, so i don't really understand what LINQ is...
Your answer
Follow this Question
Related Questions
How to instantiate prefabs at random postions in 2d 1 Answer
Multiple Cars not working 1 Answer
Generate new blocks to land on 1 Answer
Distribute terrain in zones 3 Answers
How can I randomly create a number and then delete it to stop repeating 3 Answers