BotSpawner.cs

Component that spawns GameObject bots on a timed interval. It tracks spawned instances, enforces a max count, can clear existing bots when bots are disabled, and network-spawns instances when networking is active.

NetworkingFile Access
using Sandbox;
using System;
using System.Collections.Generic;

public sealed class BotSpawner : Component
{
    [Property] public GameObject BotPrefab { get; set; }
    [Property] public float SpawnInterval { get; set; } = 4f;
    [Property] public int MaxBots { get; set; } = 5;

    public static bool EnableBots { get; set; } = true;

    private List<GameObject> _activeBots = new();
    private TimeSince _timeSinceLastSpawn = 0;

    protected override void OnUpdate()
    {
        if ( IsProxy ) return;

        // Если боты выключены в настройках — удаляем уже заспавненных
        if ( !EnableBots )
        {
            if ( _activeBots.Count > 0 )
            {
                foreach ( var bot in _activeBots )
                {
                    if ( bot.IsValid() ) bot.Destroy();
                }
                _activeBots.Clear();
            }
            return;
        }

        if ( _timeSinceLastSpawn > SpawnInterval )
        {
            _timeSinceLastSpawn = 0;
            SpawnBot();
        }
    }

    private void SpawnBot()
    {
        if ( !BotPrefab.IsValid() )
        {
            Log.Warning( "[BotSpawner] BotPrefab не назначен в Инспекторе!" );
            return;
        }

        _activeBots.RemoveAll( bot => !bot.IsValid() );

        if ( _activeBots.Count >= MaxBots ) return;

        // Спавн относительно позиции спавнера
        var randomX = Random.Shared.Float( -150f, 150f );
        var randomY = Random.Shared.Float( -150f, 150f );
        var spawnPos = WorldPosition + new Vector3( randomX, randomY, 200f );

        var botInstance = BotPrefab.Clone( spawnPos );
        if ( !botInstance.IsValid() ) return;

        _activeBots.Add( botInstance );

        if ( Network.Active )
        {
            botInstance.NetworkSpawn();
        }

        Log.Info( $"[BotSpawner] Бот заспавнен в {spawnPos}" );
    }
}