quero aplicar o:
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
na hora de ProvideRecyclerToPlayer e OnEntityBuilt, modifique e me mande o código completo
Assistant
User
faça uma função para quando uma recycler for destruida remover todos entitys filhas dela serem removidas de _entitysOnRecyclers
Assistant
User
Assistant
#region Game Hooks
private void Init()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
}
}
private void OnServerInitialized()
{
_instance = this;
var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
foreach (var recycler in existingRecyclers)
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerManager>();
}
}
}
private void Unload()
{
var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
foreach (var recycler in recyclers)
{
UnityEngine.Object.Destroy(recycler);
}
_entitysOnRecyclers.Clear();
_playersRecyclers.Clear();
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (container?.entityOwner is Recycler recycler && _entitysOnRecyclers.TryGetValue(recycler.net.ID.Value, out var recyclerManager))
{
HandleItemsInRecycler(recyclerManager, item);
}
}
private void OnEntityBuilt(Planner planner, GameObject buildingObject)
{
var player = planner?.GetOwnerPlayer();
var entity = buildingObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
return;
if (!DeployRecyclerSetup(player, entity))
{
player.ChatMessage("Recycler must be placed on a construction block.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
}
NextTick(() => entity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
{
_entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
ProvideRecyclerToPlayer(player);
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
{
_playersRecyclers.Remove(recycler.net.ID.Value);
}
return null;
}
#endregion
#region Main
private void HandleTestCommand(BasePlayer player, string command, string[] args)
{
ProvideRecyclerToPlayer(player);
}
private void ProvideRecyclerToPlayer(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
recyclerItem.name = "Recycler";
player.inventory.GiveItem(recyclerItem);
}
private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
{
var foundationBlock = DetectSupportingFoundation(entity);
if (foundationBlock == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
return true;
}
private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
return hitInfo.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
if (recycler == null)
return null;
var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));
return recycler;
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
{
if (item.position < 6)
{
recyclerManager.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerManager.OutputContainer.inventory))
{
recyclerManager.Recycler.StopRecycling();
}
}
}
#endregion
#region Configs
private class PluginConfig
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfiguration();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfiguration()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Commands = new List<string> { "teste", "testee", "testeeee" },
Limit = 1,
Version = Version,
};
}
#endregion
#region MonoBehaviour
private class RecyclerManager : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);
if (InputContainer == null || OutputContainer == null)
{
Destroy(this);
_instance.PrintError("Storage containers missing.");
return;
}
var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorInputContainer != null)
_instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;
var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorOutputContainer != null)
_instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;
_instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
_instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;
InputContainer.inventory.capacity = 48;
OutputContainer.inventory.capacity = 48;
InvokeRepeating(nameof(MoveItemsToRecycler), 0f, 20f);
}
private void MoveItemsToRecycler()
{
int nextSlot = 0;
foreach (var item in InputContainer.inventory.itemList.ToList())
{
if (nextSlot >= 6)
break;
if (Recycler.inventory.GetSlot(nextSlot) == null)
{
item.MoveToContainer(Recycler.inventory, nextSlot);
nextSlot++;
}
}
}
private void OnDestroy()
{
CancelInvoke(nameof(MoveItemsToRecycler));
}
}
#endregion
}
}
The provided code is a plugin for the game Rust, written for the uMod plugin framework. This plugin, named "IndustrialRecycler," is designed to automate recycling processes by allowing players to attach storage and adaptor components to recyclers. Below, I'll provide a summary and some key parts of the code:
Key Features
Recycler Setup and Management:
Automatically manages recycler components by associating input and output storage containers with a recycler unit.
Supports automatic recycling of items placed in the recycler's input container.
Player Interaction:
Players can interact with recyclers using custom chat commands defined in the configuration, such as obtaining a recycler setup or deploying a recycler setup on a valid construction block.
Configuration:
The plugin uses a simple configuration file to define custom commands and limitations.
Automatically updates the configuration if a new version of the plugin introduces changes.
Entity Management:
Implements handlers for various server events, such as adding items to a recycler's container, building entities, picking up entities, and recycling management.
Important Code Sections
Initialization and Server Hooks:
Init(): Registers chat commands from the configuration.
OnServerInitialized(): Attaches the RecyclerManager component to existing recyclers on the server.
Unload(): Safely removes all components and cleans up dictionaries when the plugin is unloaded.
Item and Entity Handling:
OnItemAddedToContainer(): Automatically starts recycling when items are added to the recycler's input container.
OnEntityBuilt(): Validates and sets up a recycler when a small generator is placed by a player (transformed into a recycler if conditions are met).
Recycler and Storage Management:
DeployRecyclerSetup(): Sets up a recycler with associated components (storage, adaptors) on a valid foundation block.
RecyclerManager MonoBehaviour: Handles logic for transferring items from the input storage container into the recycler and starts the recycling process.
Configuration Management:
LoadConfig(), LoadDefaultConfig(), SaveConfig(): Manages loading, saving, and updating the plugin's configuration file.
Considerations
Ensure that the uMod framework and the plugin dependencies like GameManager, Recycle, ItemManager, and specific prefab and path identifiers are correctly set up in the Rust server environment.
The plugin relies on the assumption that certain prefabs and entities exist and are correctly named. Admins might need to verify or adjust these if updates to Rust change prefab paths or entity structures.
Check compatibility with Rust server updates, as changes in Rust's codebase or networking might affect how entities and items are handled.
This plugin is heavily integrated into Rust's game mechanics and allows server administrators to provide a more efficient recycling system for players by automating interactions with recyclers.
Para aplicar o limite de recicladores por jogador ao método ProvideRecyclerToPlayer e ao evento OnEntityBuilt, precisaremos alterar o código para verificar se o jogador já possui o número máximo permitido de recicladores antes de fornecer ou criar um novo. Farei as modificações necessárias no seu código e fornecerei o código completo atualizado.
Código Atualizado:
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.0.0")]
[Description("Automate recycling by attaching storage and adaptors to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region Fields
private static IndustrialRecycler _instance;
private PluginConfig _config;
private Dictionary<ulong, RecyclerManager> _entitysOnRecyclers = new Dictionary<ulong, RecyclerManager>();
private Dictionary<ulong, ulong> _playersRecyclers = new Dictionary<ulong, ulong>();
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string StorageInputPrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string StorageOutputPrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdaptorPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string SmallGeneratorPrefabName = "electric.generator.small";
private const ulong RecyclerSkinID = 3341430953;
#endregion
#region Game Hooks
private void Init()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
}
}
private void OnServerInitialized()
{
_instance = this;
var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
foreach (var recycler in existingRecyclers)
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerManager>();
}
}
}
private void Unload()
{
var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
foreach (var recycler in recyclers)
{
UnityEngine.Object.Destroy(recycler);
}
_entitysOnRecyclers.Clear();
_playersRecyclers.Clear();
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (container?.entityOwner is Recycler recycler && _entitysOnRecyclers.TryGetValue(recycler.net.ID.Value, out var recyclerManager))
{
HandleItemsInRecycler(recyclerManager, item);
}
}
private void OnEntityBuilt(Planner planner, GameObject buildingObject)
{
var player = planner?.GetOwnerPlayer();
var entity = buildingObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
return;
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
NextTick(() => entity?.Kill());
return;
}
if (!DeployRecyclerSetup(player, entity))
{
player.ChatMessage("Recycler must be placed on a construction block.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
}
NextTick(() => entity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
{
_entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
ProvideRecyclerToPlayer(player);
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
{
_playersRecyclers.Remove(recycler.net.ID.Value);
}
return null;
}
#endregion
#region Main
private void HandleTestCommand(BasePlayer player, string command, string[] args)
{
ProvideRecyclerToPlayer(player);
}
private void ProvideRecyclerToPlayer(BasePlayer player)
{
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
return;
}
var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
recyclerItem.name = "Recycler";
player.inventory.GiveItem(recyclerItem);
}
private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
{
var foundationBlock = DetectSupportingFoundation(entity);
if (foundationBlock == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
return true;
}
private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
return hitInfo.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
if (recycler == null)
return null;
var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));
return recycler;
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
{
if (item.position < 6)
{
recyclerManager.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerManager.OutputContainer.inventory))
{
recyclerManager.Recycler.StopRecycling();
}
}
}
#endregion
#region Configs
private class PluginConfig
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfiguration();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfiguration()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Commands = new List<string> { "teste", "testee", "testeeee" },
Limit = 1,
Version = Version,
};
}
#endregion
#region MonoBehaviour
private class RecyclerManager : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);
if (InputContainer == null || OutputContainer == null)
{
Destroy(this);
_instance.PrintError("Storage containers missing.");
return;
}
var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorInputContainer != null)
_instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;
var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorOutputContainer != null)
_instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;
_instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
_instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;
InputContainer.inventory.capacity = 48;
OutputContainer.inventory.capacity = 48;
InvokeRepeating(nameof(MoveItemsToRecycler), 0f, 20f);
}
private void MoveItemsToRecycler()
{
int nextSlot = 0;
foreach (var item in InputContainer.inventory.itemList.ToList())
{
if (nextSlot >= 6)
break;
if (Recycler.inventory.GetSlot(nextSlot) == null)
{
item.MoveToContainer(Recycler.inventory, nextSlot);
nextSlot++;
}
}
}
private void OnDestroy()
{
CancelInvoke(nameof(MoveItemsToRecycler));
}
}
#endregion
}
}
Modificações Realizadas:
No método ProvideRecyclerToPlayer, adicionei uma verificação para garantir que o jogador não exceda o limite de recicladores definido no arquivo de configuração.
No evento OnEntityBuilt, adicionei uma verificação similar para impedir que um novo reciclador seja criado se o jogador já estiver no limite.
Mensagens de alerta foram adicionadas para notificar o jogador quando eles atingiram o limite de recicladores.
Agora, ao executar qualquer uma dessas ações, o plugin verificará o limite do jogador e impedirá ações que interfiram com as restrições definidas.
Para garantir que todas as entidades filhas de um Recycler sejam removidas do dicionário _entitysOnRecyclers quando o próprio Recycler for destruído, você pode criar uma função que percorra todas as entidades filhas e as remova do dicionário. Isso deve ser chamado quando o Recycler for destruído. Vou implementar isso no código fornecido.
Código Atualizado:
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.0.0")]
[Description("Automate recycling by attaching storage and adaptors to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region Fields
private static IndustrialRecycler _instance;
private PluginConfig _config;
private Dictionary<ulong, RecyclerManager> _entitysOnRecyclers = new Dictionary<ulong, RecyclerManager>();
private Dictionary<ulong, ulong> _playersRecyclers = new Dictionary<ulong, ulong>();
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string StorageInputPrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string StorageOutputPrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdaptorPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string SmallGeneratorPrefabName = "electric.generator.small";
private const ulong RecyclerSkinID = 3341430953;
#endregion
#region Game Hooks
private void Init()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
}
}
private void OnServerInitialized()
{
_instance = this;
var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
foreach (var recycler in existingRecyclers)
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerManager>();
}
}
}
private void Unload()
{
var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
foreach (var recycler in recyclers)
{
UnityEngine.Object.Destroy(recycler);
}
_entitysOnRecyclers.Clear();
_playersRecyclers.Clear();
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (container?.entityOwner is Recycler recycler && _entitysOnRecyclers.TryGetValue(recycler.net.ID.Value, out var recyclerManager))
{
HandleItemsInRecycler(recyclerManager, item);
}
}
private void OnEntityBuilt(Planner planner, GameObject buildingObject)
{
var player = planner?.GetOwnerPlayer();
var entity = buildingObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
return;
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
NextTick(() => entity?.Kill());
return;
}
if (!DeployRecyclerSetup(player, entity))
{
player.ChatMessage("Recycler must be placed on a construction block.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
}
NextTick(() => entity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
{
_entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
ProvideRecyclerToPlayer(player);
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
{
_playersRecyclers.Remove(recycler.net.ID.Value);
}
RemoveRecyclerEntities(recycler);
return null;
}
#endregion
#region Main
private void HandleTestCommand(BasePlayer player, string command, string[] args)
{
ProvideRecyclerToPlayer(player);
}
private void ProvideRecyclerToPlayer(BasePlayer player)
{
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
return;
}
var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
recyclerItem.name = "Recycler";
player.inventory.GiveItem(recyclerItem);
}
private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
{
var foundationBlock = DetectSupportingFoundation(entity);
if (foundationBlock == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
return true;
}
private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
return hitInfo.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
if (recycler == null)
return null;
var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));
return recycler;
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
{
if (item.position < 6)
{
recyclerManager.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerManager.OutputContainer.inventory))
{
recyclerManager.Recycler.StopRecycling();
}
}
}
private void RemoveRecyclerEntities(Recycler recycler)
{
var children = recycler.children.OfType<BaseEntity>();
foreach (var child in children)
{
if (_entitysOnRecyclers.ContainsKey(child.net.ID.Value))
{
_entitysOnRecyclers.Remove(child.net.ID.Value);
}
}
if (_entitysOnRecyclers.ContainsKey(recycler.net.ID.Value))
{
_entitysOnRecyclers.Remove(recycler.net.ID.Value);
}
}
#endregion
#region Configs
private class PluginConfig
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfiguration();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfiguration()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Commands = new List<string> { "teste", "testee", "testeeee" },
Limit = 1,
Version = Version,
};
}
#endregion
#region MonoBehaviour
private class RecyclerManager : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);
if (InputContainer == null || OutputContainer == null)
{
Destroy(this);
_instance.PrintError("Storage containers missing.");
return;
}
var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorInputContainer != null)
_instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;
var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorOutputContainer != null)
_instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;
_instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
_instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;
InputContainer.inventory.capacity = 48;
OutputContainer.inventory.capacity = 48;
InvokeRepeating(nameof(MoveItemsToRecycler), 0f, 20f);
}
private void MoveItemsToRecycler()
{
int nextSlot = 0;
foreach (var item in InputContainer.inventory.itemList.ToList())
{
if (nextSlot >= 6)
break;
if (Recycler.inventory.GetSlot(nextSlot) == null)
{
item.MoveToContainer(Recycler.inventory, nextSlot);
nextSlot++;
}
}
}
private void OnDestroy()
{
CancelInvoke(nameof(MoveItemsToRecycler));
}
}
#endregion
}
}
Modificações Realizadas:
Função RemoveRecyclerEntities:
Esta função é chamada quando uma Recycler é destruída (OnEntityKill).
Ela itera sobre todas as entidades filhas de um Recycler e remove suas IDs do dicionário _entitysOnRecyclers.
Também remove a própria Recycler do dicionário.
Certifique-se de que a função RemoveRecyclerEntities é chamada sempre que um Recycler é destruído para garantir que toda a limpeza necessária de dados seja realizada.
esse é meu código agora, quero que quando entrar items no container input, sejam automaticamente transferidos para os os seis primeiros slots da recycler, usando o OnItemAddedToContainer:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
#region Game Hooks
private void Init()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
}
}
private void OnServerInitialized()
{
_instance = this;
var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
foreach (var recycler in existingRecyclers)
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerManager>();
}
}
}
private void Unload()
{
var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
foreach (var recycler in recyclers)
{
UnityEngine.Object.Destroy(recycler);
}
_entitysOnRecyclers.Clear();
_playersRecyclers.Clear();
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (container?.entityOwner is Recycler recycler && _entitysOnRecyclers.TryGetValue(recycler.net.ID.Value, out var recyclerManager))
{
HandleItemsInRecycler(recyclerManager, item);
}
}
private void OnEntityBuilt(Planner planner, GameObject buildingObject)
{
var player = planner?.GetOwnerPlayer();
var entity = buildingObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
return;
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
NextTick(() => entity?.Kill());
return;
}
if (!DeployRecyclerSetup(player, entity))
{
player.ChatMessage("Recycler must be placed on a construction block.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
}
NextTick(() => entity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
{
_entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
ProvideRecyclerToPlayer(player);
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
{
_playersRecyclers.Remove(recycler.net.ID.Value);
RemoveRecyclerEntities(recycler);
}
return null;
}
#endregion
#region Main
private void HandleTestCommand(BasePlayer player, string command, string[] args)
{
ProvideRecyclerToPlayer(player);
}
private void ProvideRecyclerToPlayer(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
recyclerItem.name = "Recycler";
player.inventory.GiveItem(recyclerItem);
}
private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
{
var foundationBlock = DetectSupportingFoundation(entity);
if (foundationBlock == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
return true;
}
private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
return hitInfo.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
if (recycler == null)
return null;
var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));
return recycler;
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
{
if (item.position < 6)
{
recyclerManager.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerManager.OutputContainer.inventory))
{
recyclerManager.Recycler.StopRecycling();
}
}
}
private void RemoveRecyclerEntities(Recycler recycler)
{
var children = recycler.children;
foreach (var child in children)
{
if (_entitysOnRecyclers.ContainsKey(child.net.ID.Value))
{
_entitysOnRecyclers.Remove(child.net.ID.Value);
}
}
if (_entitysOnRecyclers.ContainsKey(recycler.net.ID.Value))
{
_entitysOnRecyclers.Remove(recycler.net.ID.Value);
}
}
#endregion
#region Configs
private class PluginConfig
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfiguration();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfiguration()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Commands = new List<string> { "teste", "testee", "testeeee" },
Limit = 1,
Version = Version,
};
}
#endregion
#region MonoBehaviour
private class RecyclerManager : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);
if (InputContainer == null || OutputContainer == null)
{
Destroy(this);
_instance.PrintError("Storage containers missing.");
return;
}
var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorInputContainer != null)
_instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;
var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorOutputContainer != null)
_instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;
_instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
_instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;
InputContainer.inventory.capacity = 48;
OutputContainer.inventory.capacity = 48;
InvokeRepeating(nameof(MoveItemsToRecycler), 0f, 20f);
}
private void MoveItemsToRecycler()
{
int nextSlot = 0;
foreach (var item in InputContainer.inventory.itemList.ToList())
{
if (nextSlot >= 6)
break;
if (Recycler.inventory.GetSlot(nextSlot) == null)
{
item.MoveToContainer(Recycler.inventory, nextSlot);
nextSlot++;
}
}
}
private void OnDestroy()
{
CancelInvoke(nameof(MoveItemsToRecycler));
}
}
#endregion
}
}
Para fazer com que os itens no contêiner de entrada sejam automaticamente transferidos para os seis primeiros slots do reciclador (Recycler), devemos modificar o método OnItemAddedToContainer para lidar com essa transferência quando um item é adicionado ao contêiner de entrada. Vou ajustar o seu código para incorporar essa funcionalidade.
Código Atualizado
Aqui está o código modificado com a funcionalidade solicitada:
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.0.0")]
[Description("Automate recycling by attaching storage and adaptors to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region Fields
private static IndustrialRecycler _instance;
private PluginConfig _config;
private Dictionary<ulong, RecyclerManager> _entitysOnRecyclers = new Dictionary<ulong, RecyclerManager>();
private Dictionary<ulong, ulong> _playersRecyclers = new Dictionary<ulong, ulong>();
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string StorageInputPrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string StorageOutputPrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdaptorPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string SmallGeneratorPrefabName = "electric.generator.small";
private const ulong RecyclerSkinID = 3341430953;
#endregion
#region Game Hooks
private void Init()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
}
}
private void OnServerInitialized()
{
_instance = this;
var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
foreach (var recycler in existingRecyclers)
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerManager>();
}
}
}
private void Unload()
{
var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
foreach (var recycler in recyclers)
{
UnityEngine.Object.Destroy(recycler);
}
_entitysOnRecyclers.Clear();
_playersRecyclers.Clear();
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (container?.entityOwner is StorageContainer inputContainer
&& inputContainer.name == StorageInputPrefabPath
&& _entitysOnRecyclers.TryGetValue(inputContainer.net.ID.Value, out var recyclerManager))
{
TransferItemsToRecycler(recyclerManager, item);
}
}
private void OnEntityBuilt(Planner planner, GameObject buildingObject)
{
var player = planner?.GetOwnerPlayer();
var entity = buildingObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
return;
if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
{
player.ChatMessage("You have reached the recycler limit.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
NextTick(() => entity?.Kill());
return;
}
if (!DeployRecyclerSetup(player, entity))
{
player.ChatMessage("Recycler must be placed on a construction block.");
timer.Once(1, () => ProvideRecyclerToPlayer(player));
}
NextTick(() => entity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
{
_entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
ProvideRecyclerToPlayer(player);
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
{
_playersRecyclers.Remove(recycler.net.ID.Value);
RemoveRecyclerEntities(recycler);
}
return null;
}
#endregion
#region Main
private void HandleTestCommand(BasePlayer player, string command, string[] args)
{
ProvideRecyclerToPlayer(player);
}
private void ProvideRecyclerToPlayer(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
recyclerItem.name = "Recycler";
player.inventory.GiveItem(recyclerItem);
}
private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
{
var foundationBlock = DetectSupportingFoundation(entity);
if (foundationBlock == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
return true;
}
private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
return hitInfo.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
if (recycler == null)
return null;
var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));
return recycler;
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void TransferItemsToRecycler(RecyclerManager recyclerManager, Item item)
{
// Try to move the item to one of the first 6 slots in the recycler.
for (int i = 0; i < 6; i++)
{
if (recyclerManager.Recycler.inventory.GetSlot(i) == null)
{
item.MoveToContainer(recyclerManager.Recycler.inventory, i);
return;
}
}
// If all 6 slots are occupied, leave the item in the input container.
// Optionally, you could handle overflow here or send a notification to the player.
}
private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
{
// Starts the recycling process if items are present in the slots
recyclerManager.Recycler.StartRecycling();
}
private void RemoveRecyclerEntities(Recycler recycler)
{
var children = recycler.children;
foreach (var child in children)
{
if (_entitysOnRecyclers.ContainsKey(child.net.ID.Value))
{
_entitysOnRecyclers.Remove(child.net.ID.Value);
}
}
if (_entitysOnRecyclers.ContainsKey(recycler.net.ID.Value))
{
_entitysOnRecyclers.Remove(recycler.net.ID.Value);
}
}
#endregion
#region Configs
private class PluginConfig
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Limit Per Player")]
public int Limit { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfiguration();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfiguration()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Commands = new List<string> { "teste", "testee", "testeeee" },
Limit = 1,
Version = Version,
};
}
#endregion
#region MonoBehaviour
private class RecyclerManager : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);
if (InputContainer == null || OutputContainer == null)
{
Destroy(this);
_instance.PrintError("Storage containers missing.");
return;
}
var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorInputContainer != null)
_instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;
var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (adaptorOutputContainer != null)
_instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;
_instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
_instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;
InputContainer.inventory.capacity = 48;
OutputContainer.inventory.capacity = 48;
}
}
#endregion
}
}
Modificações Feitas:
OnItemAddedToContainer:
Modificado para verificar se o container é o InputContainer e, se assim for, chamar TransferItemsToRecycler.
TransferItemsToRecycler:
Tenta transferir o item adicionado para um dos seis primeiros slots no inventário da Recycler, se possível.
HandleItemsInRecycler:
Neste exemplo, está iniciando o processo de reciclagem sempre que um item é transferido para o Recycler. Isso garante que o processo de reciclagem comece automaticamente quando há itens para reciclar.
Essas alterações garantem que itens no contêiner de entrada sejam automaticamente realocados para o Recycler assim que adicionados, conforme solicitado.