Hi I'm currently making a small game that will have "random" loot drop after an enemy dies.
Quite new to c# and unity as well.
What I'm doing here is having the itemtype, prefixtype & suffixtype as Scriptable objects the lists are pulling from Classes. Then having it randomly roll for the stats with the dice.
But I'm stuck on how i would output all three of these as 1 singular item after all three have been rolled for. So for example, ItemBase(Sword) => PrefixType (Chilled) => SuffixType (Of the Base) and then output it as one singular item rather than three individual stats.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Main : MonoBehaviour
{
[SerializeField] public List<Item> itemType = new List<Item>();
[SerializeField] public List<Prefix> prefixType = new List<Prefix>();
[SerializeField] public List<Suffix> suffixType = new List<Suffix>();
[System.NonSerialized] private bool isInitialized = false;
private float _totalWeight;
private float _suffixWeight;
private float _prefixWeight;
private void Update()
{
GetRandomItem();
GetRandomPrefix();
GetRandomSuffix();
}
private void ItemInitialize()
{
if (!isInitialized)
{
_totalWeight = itemType.Sum(item => item.weight);
_prefixWeight = prefixType.Sum(prefix => prefix.weight);
_suffixWeight = suffixType.Sum(suffix => suffix.weight);
isInitialized = true;
}
}
public Item GetRandomItem()
{
// Make sure it is initalized
ItemInitialize();
// Roll our dice with _totalWeight faces
float diceRoll = Random.Range(0f, _totalWeight);
// Cycle through our items
foreach (var item in itemType)
{
if (item.weight >= diceRoll)
{
Debug.Log("Item: " + item.itemName);
return item;
}
// If we didn't return, we substract the weight to our diceRoll and cycle to the next item
diceRoll -= item.weight;
}
// Spooky Error.
throw new System.Exception("Reward generation failed!");
}
public Prefix GetRandomPrefix()
{
// Roll our dice with _totalWeight faces
float diceRoll = Random.Range(0f, _prefixWeight);
// Cycle through our items
foreach (var prefix in prefixType)
{
if (prefix.weight >= diceRoll)
{
Debug.Log("Item: " + prefix.prefixName);
return prefix;
}
// If we didn't return, we substract the weight to our diceRoll and cycle to the next item
diceRoll -= prefix.weight;
}
// Spooky Error.
throw new System.Exception("Reward generation failed!");
}
public Suffix GetRandomSuffix()
{
// Roll our dice with _totalWeight faces
float diceRoll = Random.Range(0f, _suffixWeight);
// Cycle through our items
foreach (var suffix in suffixType)
{
if (suffix.weight >= diceRoll)
{
Debug.Log("Item: " + suffix.suffixName);
return suffix;
}
// If we didn't return, we substract the weight to our diceRoll and cycle to the next item
diceRoll -= suffix.weight;
}
// Spooky Error.
throw new System.Exception("Reward generation failed!");
}
}