Added spawn weighting

This commit is contained in:
Pasha Bibko
2026-01-15 13:20:04 +00:00
parent cf10bf3f90
commit a155d85f72
7 changed files with 221 additions and 14 deletions

View File

@@ -1,37 +1,60 @@
using System;
using System.Collections.Generic;
using Ext.B83.Unity.Attributes;
using UnityEngine;
using Random = UnityEngine.Random;
namespace InterfaceOff
{
[Serializable] public struct SpawnableWindowType
{
[field: SerializeField, MonoScript] private string Typename { get; set; }
public Type Type => Type.GetType(Typename);
[field: SerializeField] public int SpawnWeight { get; private set; }
}
public class WindowSpawner : MonoBehaviour
{
private List<Type> WindowTypes { get; } = new();
[field: SerializeField] private GameObject SampleChild { get; set; }
[field: SerializeField] private Canvas GameCanvas { get; set; }
[field: SerializeField] private SpawnableWindowType[] WindowTypes { get; set; }
private int TotalSpawnWeight { get; set; }
[field: SerializeField] public bool AutoSpawn { get; private set; } = true;
private void Awake()
{
/* Fetches all window types created */
Type[] types = typeof(WindowBase).Assembly.GetTypes();
foreach (Type t in types)
/* Logs the amount of types found and errors if there is none */
Debug.Log($"Found [{WindowTypes.Length}] different window types ");
if (WindowTypes.Length == 0)
{
if (t.IsSubclassOf(typeof(WindowBase)))
Debug.LogError("Could not find any window types");
return;
}
/* Calculates the total spawn weight */
TotalSpawnWeight = 0;
foreach (SpawnableWindowType type in WindowTypes)
{
TotalSpawnWeight += type.SpawnWeight;
}
}
private Type GetRandomWindowType()
{
int currentTypeWeight = Random.Range(0, TotalSpawnWeight);
foreach (SpawnableWindowType type in WindowTypes)
{
currentTypeWeight -= type.SpawnWeight;
if (currentTypeWeight <= 0)
{
WindowTypes.Add(t);
return type.Type;
}
}
/* Logs the amount of types found and errors if there is none */
Debug.Log($"Found [{WindowTypes.Count}] different window types ");
if (WindowTypes.Count == 0)
{
Debug.LogError("Could not find any window types");
}
return WindowTypes[0].Type;
}
private void SpawnNewRandomWindow()
@@ -40,7 +63,7 @@ namespace InterfaceOff
GameObject go = Instantiate(SampleChild, GameCanvas.transform);
go.SetActive(true);
Type type = WindowTypes.GetRandom();
Type type = GetRandomWindowType();
go.name = type.Name;
WindowBase windowBase = go.AddComponent(type) as WindowBase;