using System.Linq;
using System.Collections.Generic;
using UnityEngine;

public class PopulateRandomSlots : MonoBehaviour
{
    public HazardData[] Hazards;
    public int MinObjects;
    public int MaxObjects;

    void Start()
    {
        int hazardsAmount = Random.Range(MinObjects, MaxObjects);
        Hazards = Hazards.OrderBy(item => item.Chance).ToArray();

        List<Transform> spots = new List<Transform>();

        for (int i = 0; i < transform.childCount; i++)
            spots.Add(transform.GetChild(i));

        for (int i = 0; i < hazardsAmount; i++)
        {
            int spotIndex = Random.Range(0, spots.Count);
            int hazardIndex = -1;

            float rnd = Random.Range(0f, 100f);
            float addedChance = 0;

            for (int j = 0; j < Hazards.Length; j++)
            {
                addedChance += Hazards[j].Chance;
                if (rnd < addedChance)
                {
                    hazardIndex = j;
                    break;
                }
            }

            Instantiate(Hazards[hazardIndex].Prefab, spots[spotIndex].position, Quaternion.identity);

            spots.RemoveAt(spotIndex);
        }
    }
}

[System.Serializable]
public struct HazardData
{
    public GameObject Prefab;
    [Range(0, 100)]
    public float Chance;
}