refatore este plugin: using System.Collections.Generic; using Facepunch; using…
- User
refatore este plugin: using System.Collections.Generic; using Facepunch; using Newtonsoft.Json; using Rust; using UnityEngine; using Random = UnityEngine.Random;
namespace Oxide.Plugins { [Info("ChristmasDungeon", "Marte6", "1.1.0")] public class ChristmasDungeon : RustPlugin { private static PluginConfig _config; private Timer _autoSpawnTimer; private const string DungeonPrefabPath = "assets/prefabs/missions/portal/xmasportalentry.prefab";
private XmasDungeon _currentDungeon; private void Init() { LoadConfig(); if (_config.EnableAutoSpawn) { StartAutoSpawnTimer(); } } protected override void LoadConfig() { base.LoadConfig(); _config = Config.ReadObject<PluginConfig>(); if (string.Compare(_config.Version, Version.ToString()) < 0) { UpdateConfig(); } SaveConfig(); } protected override void LoadDefaultConfig() { _config = GetDefaultConfig(); } protected override void SaveConfig() { Config.WriteObject(_config, true); } private void UpdateConfig() { PrintWarning("Config changes detected! Updating..."); var defaultConfig = GetDefaultConfig(); if (string.Compare(_config.Version, "1.1.0") < 0) { _config = defaultConfig; } PrintWarning($"Config update complete! Updated from version {_config.Version} to {Version.ToString()}"); _config.Version = Version.ToString(); } private PluginConfig GetDefaultConfig() { return new PluginConfig { Version = Version.ToString(), EnableAutoSpawn = true, AutoSpawnIntervalMinutes = 30f, MinSpawnDistance = 6f, MaxSpawnDistance = 20f, MaxSpawnAttempts = 5, NPCSpawnConfigs = new List<NPCSpawnConfig> { new NPCSpawnConfig { PrefabName = "assets/rust.ai/agents/npcplayer/humannpc/tunneldweller/npc_tunneldweller.prefab", SpawnCount = 5 }, new NPCSpawnConfig { PrefabName = "assets/rust.ai/agents/wolf/wolf.prefab", SpawnCount = 5 }, }, }; } [ChatCommand("dun")] private void CreateDungeonCommand(BasePlayer player, string command, string[] args) { RemoveExistingDungeon(); if (FindSuitableDungeonSpawnPoint(player.transform.position, _config.MinSpawnDistance, _config.MaxSpawnDistance, out var position, out var rotation)) { _currentDungeon = CreateDungeon(position, rotation); player.ChatMessage("Christmas Dungeon created!"); } else { player.ChatMessage("Could not find a suitable location for the Christmas Dungeon."); } } private void StartAutoSpawnTimer() => _autoSpawnTimer = timer.Every(_config.AutoSpawnIntervalMinutes * 60f, AutoSpawnDungeon); private void AutoSpawnDungeon() { RemoveExistingDungeon(); for (var attempt = 0; attempt < _config.MaxSpawnAttempts; attempt++) { foreach (var player in BasePlayer.activePlayerList) { if (!FindSuitableDungeonSpawnPoint(player.transform.position, 20f, 50f, out var position, out var rotation)) continue; _currentDungeon = CreateDungeon(position, rotation); NotifyPlayersOfDungeonLocation(position); return; } } Puts("Failed to auto-spawn dungeon after max attempts."); } private void NotifyPlayersOfDungeonLocation(Vector3 position) { foreach (var player in BasePlayer.activePlayerList) { player.ChatMessage($"A Christmas Dungeon has appeared at coordinates: ({position.x:F0}, {position.z:F0})!"); } } private XmasDungeon CreateDungeon(Vector3 position, Quaternion rotation) { var entity = GameManager.server.CreateEntity(DungeonPrefabPath, position, rotation) as XmasDungeon; if (entity == null) { Puts("Failed to create dungeon entity."); return null; } entity.transform.rotation = rotation; entity.Spawn(); IntegrateNPCsInDungeon(entity); return entity; } private void IntegrateNPCsInDungeon(XmasDungeon dungeon) { Puts("Integrating NPCs in the Dungeon"); ProceduralDynamicDungeon proceduralDungeon = dungeon.dungeonInstance.Get(serverside: true); int totalCells = proceduralDungeon.spawnedCells.Count; if (totalCells == 0) { Puts("No cells found in dungeon for NPC spawns."); return; } foreach (var config in _config.NPCSpawnConfigs) { int totalNPCsAssigned = 0; int baseNPCsPerCell = config.SpawnCount / totalCells; int remainingNPCs = config.SpawnCount % totalCells; foreach (ProceduralDungeonCell spawnedCell in proceduralDungeon.spawnedCells) { if (totalNPCsAssigned >= config.SpawnCount) break; SpawnGroup spawnGroup = spawnedCell.gameObject.AddComponent<SpawnGroup>(); if (!GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid)) { Puts($"GUID not found for Prefab Name: {config.PrefabName}"); continue; } spawnGroup.prefabs = new List<SpawnGroup.SpawnEntry> { new SpawnGroup.SpawnEntry { prefab = new GameObjectRef { guid = guid }, weight = 1, mobile = true, }, }; int assignedNPCs = baseNPCsPerCell + (remainingNPCs > 0 ? 1 : 0); if (remainingNPCs > 0) { remainingNPCs--; } assignedNPCs = Mathf.Min(assignedNPCs, config.SpawnCount - totalNPCsAssigned); totalNPCsAssigned += assignedNPCs; // Set the population constraints spawnGroup.maxPopulation = assignedNPCs; spawnGroup.numToSpawnPerTickMin = 0; // Avoid re-spawning per tick spawnGroup.numToSpawnPerTickMax = 0; // Avoid re-spawning per tick spawnGroup.fillOnSpawn = true; // Fill initially and avoid further spawns Puts($"Configured spawn group in cell for {config.PrefabName} with {assignedNPCs} NPCs."); spawnGroup.Fill(); } Puts($"Finished configuring spawn groups. Total NPCs assigned: {totalNPCsAssigned}"); } } private bool FindSuitableDungeonSpawnPoint(Vector3 center, float minRadius, float maxRadius, out Vector3 suitablePosition, out Quaternion suitableRotation) { for (var attempt = 0; attempt < _config.MaxSpawnAttempts; attempt++) { var position = TerrainUtilities.GetRandomPosition(center, minRadius, maxRadius); if (IsPositionSuitable(position)) { if (TerrainUtilities.GetTerrainInfo(position, 5f, out var hitInfo)) { suitablePosition = hitInfo.point; suitableRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal); return true; } } } suitablePosition = Vector3.zero; suitableRotation = Quaternion.identity; return false; } private bool IsPositionSuitable(Vector3 position) { if (TerrainUtilities.ContainsRock(position, 2f)) return false; if (TerrainUtilities.IsInRadTown(position)) return false; if (TerrainUtilities.ContainsEntitiesNearby(position, 4f, TerrainUtilities.EntityLayerMask)) return false; if (TerrainUtilities.IsInWater(position)) return false; if (TerrainUtilities.IsOnRoadOrRail(position)) return false; if (TerrainUtilities.IsInNoBuildZone(position, 2f)) return false; return true; } private object OnPortalUse(BasePlayer player, XmasDungeon dungeon) { Puts("XmasDungeon triggered."); return null; } private void RemoveExistingDungeon() { _currentDungeon?.Kill(); _currentDungeon = null; } private void Unload() { RemoveExistingDungeon(); _autoSpawnTimer?.Destroy(); } private class PluginConfig { [JsonProperty("Version")] public string Version { get; set; } [JsonProperty("Auto Spawn Enabled")] public bool EnableAutoSpawn { get; set; } [JsonProperty("Auto Spawn Interval Minutes")] public float AutoSpawnIntervalMinutes { get; set; } [JsonProperty("Min Spawn Distance")] public float MinSpawnDistance { get; set; } [JsonProperty("Max Spawn Distance")] public float MaxSpawnDistance { get; set; } [JsonProperty("Max Spawn Attempts")] public int MaxSpawnAttempts { get; set; } [JsonProperty("NPC Spawn Configs")] public List<NPCSpawnConfig> NPCSpawnConfigs { get; set; } } private class NPCSpawnConfig { [JsonProperty("Prefab Name")] public string PrefabName { get; set; } [JsonProperty("Spawn Count")] public int SpawnCount { get; set; } } } public static class TerrainUtilities { public const int EntityLayerMask = Layers.Mask.Deployed | Layers.Mask.Construction; public const int GroundLayerMask = Layers.Mask.Terrain | Layers.Mask.World | Layers.Mask.Default; public static bool OnTopology(Vector3 position, TerrainTopology.Enum topology) { return (TerrainMeta.TopologyMap.GetTopology(position) & (int)topology) != 0; } public static bool IsOnRoadOrRail(Vector3 position) { var combinedTopology = TerrainTopology.Enum.Road | TerrainTopology.Enum.Roadside | TerrainTopology.Enum.Rail | TerrainTopology.Enum.Railside; return OnTopology(position, combinedTopology); } public static bool IsInNoBuildZone(Vector3 position, float radius) { return Physics.CheckSphere(position, radius, Layers.Mask.Prevent_Building); } public static bool IsInWater(Vector3 position) { return WaterLevel.Test(position, false, true); } public static bool ContainsRock(Vector3 position, float radius) { List<Collider> colliders = Pool.Get<List<Collider>>(); Vis.Colliders(position, radius, colliders, GroundLayerMask, QueryTriggerInteraction.Ignore); return colliders.Exists(collider => collider.name.Contains("rock", System.StringComparison.OrdinalIgnoreCase) || collider.name.Contains("cliff", System.StringComparison.OrdinalIgnoreCase) || collider.name.Contains("formation", System.StringComparison.OrdinalIgnoreCase) ); } public static bool IsInRadTown(Vector3 position) { foreach (var monumentInfo in TerrainMeta.Path.Monuments) { if (monumentInfo.IsInBounds(position) && monumentInfo.shouldDisplayOnMap) return true; } return OnTopology(position, TerrainTopology.Enum.Monument); } public static bool ContainsEntitiesNearby(Vector3 position, float radius, int mask) { List<Collider> hitColliders = Pool.Get<List<Collider>>(); GamePhysics.OverlapSphere(position, radius, hitColliders, mask, QueryTriggerInteraction.Ignore); return hitColliders.Exists(collider => collider.gameObject.ToBaseEntity() != null); } public static bool GetTerrainInfo(Vector3 startPosition, float range, out RaycastHit hitInfo) { return Physics.Linecast(startPosition + new Vector3(0f, range, 0f), startPosition - new Vector3(0f, range, 0f), out hitInfo, GroundLayerMask); } public static Vector3 GetRandomPosition(Vector3 center, float minRadius, float maxRadius) { Vector3 randomDirection = Random.onUnitSphere; randomDirection.y = 0; float randomDistance = Random.Range(minRadius, maxRadius); Vector3 randomPosition = center + randomDirection * randomDistance; randomPosition.y = TerrainMeta.HeightMap.GetHeight(randomPosition); return randomPosition; } } - Assistant
- User
Error while compiling ChristmasDungeon: The name 'LoadConfiguration' does not exist in the current context | Line: 21, Pos: 13
- Assistant
The error you're encountering is due to my mistake in renaming the method
LoadConfigtoLoadConfigurationwithin theInitmethod call, but not actually implementing aLoadConfigurationmethod in the program. Let's align the naming and ensure consistency. Here's the corrected code segment:private void Init() { LoadConfig(); // Corrected method name if (_config.EnableAutoSpawn) { StartAutoSpawnTimer(); } }The
LoadConfigurationandUpdateConfigurationreferences were mistakenly created by my explanation instead of sticking with the originalLoadConfigandUpdateConfigconventions. The rest of the code remains the same, so this change should resolve the error you encountered. If there are any other issues or you need further assistance, feel free to ask! - User
Error while compiling ChristmasDungeon: The type 'System.Collections.Generic.List' cannot be used as type parameter 'T' in the generic type or method 'Pool.Free(ref T)'. There is no implicit reference conversion from 'System.Collections.Generic.List' to 'Facepunch.Pool.IPooled'. | Line: 326, Pos: 18
- Assistant
The error you're encountering suggests that
Pool.Free(ref T)requires a parameter that implements theFacepunch.Pool.IPooledinterface, butSystem.Collections.Generic.List<T>doesn't implement this interface.To address this issue, let's ensure that we correctly use the pooling functionality provided by Facepunch. The approach would typically involve using
List<Collider>from a pooling mechanism that is compatible with Facepunch Pool.Here's how you can adapt the logic:
- User
refatore agora melhorando as funções e organizando
- Assistant
- User
remova => refatore DistributeNpcsAcrossDungeonCells, está grande
- Assistant
- User
mande a classe completa, ajsute as funções para não usarem =>
- Assistant
- User
quero que organize movendo as funções que fazem coisas parecidas para ficarem próximas e crie #regions
- Assistant