Question by
craftydeadman111 · Oct 19, 2020 at 01:47 AM ·
rng
need help random item from text file
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO;//need for reading text files using System;//need for reading text files using System.Diagnostics; using Debug = UnityEngine.Debug; using Random = UnityEngine.Random;
public class bothSystems : MonoBehaviour { string textFile = "lootList";//reference to the text file without extention located in the recouses folder.
int n = 0;
//lists to hold the text file data
public List<string> itemName;
public List<int> dropRate;
public List<int> value;
void Start()
{
ReadFromFile();
}
void ReadFromFile()
{
TextAsset textData = (TextAsset)Resources.Load(textFile, typeof(TextAsset));//loads our text file from resources folder
StringReader reader = new StringReader(textData.text);
string s = reader.ReadLine();//reads the first line of the text file
//Debug.Log(s);//displays the full line of text unsplit
while (s != null)
{
char[] delimiter = { ',' }; //sets the delimiter value for the text file
string[] fields = s.Split(delimiter);//splits the text line at each instance of a comma (the delimiter)
//copy the split sections to the relevant lists
itemName.Add(fields[0]);
dropRate.Add(int.Parse(fields[1]));
value.Add(int.Parse(fields[2]));
Debug.Log(itemName[n]);
Debug.Log(dropRate[n]);
Debug.Log(value[n]);
n++;
s = reader.ReadLine();//reads the next line of the text file
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
int n = RandomItem();//call fuction to recieve random loot drop
}
}
int RandomItem()
{
//develop the ange to randomise from
int range = 0;
int i; //counter
for (i = 0; i < dropRate.Count; i++)
{
range += dropRate[i];
}
//generate random number signifying the loot item
int rand = Random.Range(0, range);
int top = 0;
for (i = 0; i < dropRate.Count; i++)
{
top += dropRate[i];//adding the array drop rates to increase the upper limit of the check
//testing to see if rand umber is less then the cumalative drop rate
if (rand < top)
{
break;//if true stops the loop
}
}
Debug.Log("Random roll: " + rand);//distplays our random number
Debug.Log("Top value: " + top);//displays the upper limit of the columitive drop rate
return i;//returns the index to the loot drop
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613014104im_/https://answers.unity.com/themes/thub/images/avi.jpg)