using System.Collections.Generic; using UnityEngine; namespace DanroJump.Gameplay { [System.Serializable] public sealed class WeightedPrefabOption { [SerializeField] private GameObject prefab; [SerializeField] [Min(0f)] private float weight = 1f; public GameObject Prefab => prefab; public float Weight => weight; public static bool TrySelect(IReadOnlyList options, System.Random random, out GameObject prefab) { prefab = null; var totalWeight = 0f; if (options == null) { return false; } foreach (var option in options) { if (option?.Prefab != null && option.Weight > 0f) { totalWeight += option.Weight; } } if (totalWeight <= 0f) { return false; } var roll = (float)((random != null ? random.NextDouble() : 0d) * totalWeight); foreach (var option in options) { if (option?.Prefab == null || option.Weight <= 0f) { continue; } roll -= option.Weight; if (roll <= 0f) { prefab = option.Prefab; return true; } } return false; } } }