0
votes

I have a basic loot table with weighted drop rarities. I am trying to make it so that when the game starts, it will re-roll if the item already exists in a duplicated list.

I've created an empty list in shopManagerScript and am adding each instantiated item to that list. Then I would like to check against that list to see if the item exists. If it does, I want to re-roll again. If it doesn't then go ahead and instantiate the item.

This current code is executing endlessly however, and is crashing my game.

public GameObject shopManager;
public ShopManager shopManagerScript;

[System.Serializable]
public class DropItem
{
    public string name;
    public GameObject item;
    public int dropRarity;
}

public List<DropItem> ShopItemPool = new List<DropItem>();

private void Start()
{

    shopManager = GameObject.FindGameObjectWithTag("ShopManager");
    shopManagerScript = shopManager.GetComponent<ShopManager>();
    SpawnItem();
}
void SpawnItem()
{
    int itemWeight = 0;

    for (int i = 0; i < ShopItemPool.Count; i++)
    {
        itemWeight += ShopItemPool[i].dropRarity;
    }

    int randomValue = Random.Range(0, itemWeight);

    for (int i = 0; i < ShopItemPool.Count; i++)
    {
        if (randomValue <= ShopItemPool[i].dropRarity && !shopManagerScript.shopItems.Contains(ShopItemPool[i].item.ToString()))
        {
            Instantiate(ShopItemPool[i].item, transform.position, Quaternion.identity);
            shopManagerScript.shopItems.Add(ShopItemPool[i].item.ToString());
            return;
        }
        else
        {
            SpawnItem();
        }

        randomValue -= ShopItemPool[i].dropRarity;
    }
}
If you have 2 items with the same rarity at the start of your item pool, wont this code only ever try to get the first item? Have you tried using continue instead of running the entire function again? - hijinxbassist