Помогите Не могу понять почему не работает плагин

Bratura

25 Май 2023
11
0
7
я делаю плагин для сервера, где я создаю уникальный ящик, в котором будут спавнятся ресурсы, ну металл камень и тд.
можете помочь?
Код:
using System;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("BoxPlugin", "Bratura", "1.0.0")]
    [Description("Spawns resources in a box placed by a player")]
    public class BoxPlugin : RustPlugin
    {
        private const string Permission_Use = "boxplugin.use";

        private void Init()
        {
            permission.RegisterPermission(Permission_Use, this);
            AddCovalenceCommand("box", "CmdBox");
            Subscribe<Action<Deployer, BaseEntity>>(nameof(OnItemDeployed));

            Puts("BoxPlugin: Initialized");
        }

        private void CmdBox(IPlayer player, string command, string[] args)
        {
            if (!player.HasPermission(Permission_Use))
            {
                player.Reply("You don't have permission to use this command.");
                return;
            }

            var basePlayer = player.Object as BasePlayer;
            if (basePlayer != null)
            {
                var boxDefinition = ItemManager.FindItemDefinition("box.wooden.large");
                if (boxDefinition != null)
                {
                    var boxItem = ItemManager.CreateByItemID(boxDefinition.itemid, 1);
                    if (boxItem != null)
                    {
                        basePlayer.GiveItem(boxItem);
                    }
                }
            }
            Puts($"BoxPlugin: {player.Name} used /box command");
        }

        private void OnItemDeployed(Deployer deployer, BaseEntity deployedEntity)
        {
            var storageContainer = deployedEntity as StorageContainer;
            if (storageContainer == null) return;

            if (deployedEntity.PrefabName.Contains("box.wooden.large"))
            {
                Puts("Player placed a box");

                if (storageContainer != null)
                {
                    Puts("Box built! Spawning resources...");
                    SpawnResourceInBox(storageContainer);
                }
            }
        }

        private void SpawnResourceInBox(StorageContainer boxEntity)
        {
            if (boxEntity == null || boxEntity.IsDestroyed) return;

            var resourceItem = ItemManager.CreateByName("sulfur.ore", 10);
            if (resourceItem != null)
            {
                if (!resourceItem.MoveToContainer(boxEntity.inventory))
                {
                    resourceItem.Remove();
                    return;
                }

                boxEntity.SendNetworkUpdate();
            }

            UnityEngine.Debug.Log("BoxPlugin: Resource spawned in the box");
        }
    }
}
 
Конечно, я могу помочь с созданием плагина для сервера Rust.

Прежде всего, вам понадобится установить и настроить окружение разработки для плагинов Rust. Вы можете найти подробную информацию об этом на официальном сайте Oxide: https://umod.org/documentation/games/rust/getting-started

После этого вы можете приступить к созданию плагина. Ниже приведен пример кода, который добавляет команду /box для создания и размещения уникального ящика, а также спавнит ресурсы в этом ящике при размещении:

C#:
using System;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("BoxPlugin", "Bratura", "1.0.0")]
    [Description("Spawns resources in a box placed by a player")]
    public class BoxPlugin : RustPlugin
    {
        private const string Permission_Use = "boxplugin.use";

        private void Init()
        {
            permission.RegisterPermission(Permission_Use, this);
            AddCovalenceCommand("box", "CmdBox");
            Subscribe<Action<Deployer, BaseEntity>>(nameof(OnItemDeployed));
            Puts("BoxPlugin: Initialized");
        }

        private void CmdBox(IPlayer player, string command, string[] args)
        {
            if (!player.HasPermission(Permission_Use))
            {
                player.Reply("You don't have permission to use this command.");
                return;
            }

            var basePlayer = player.Object as BasePlayer;
            if (basePlayer != null)
            {
                var boxDefinition = ItemManager.FindItemDefinition("box.wooden.large");
                if (boxDefinition != null)
                {
                    var boxItem = ItemManager.CreateByItemID(boxDefinition.itemid, 1);
                    if (boxItem != null)
                    {
                        basePlayer.GiveItem(boxItem);
                    }
                }
            }

            Puts($"BoxPlugin: {player.Name} used /box command");
        }

        private void OnItemDeployed(Deployer deployer, BaseEntity deployedEntity)
        {
            var storageContainer = deployedEntity as StorageContainer;
            if (storageContainer == null) return;

            if (deployedEntity.PrefabName.Contains("box.wooden.large"))
            {
                Puts("Player placed a box");

                if (storageContainer != null)
                {
                    Puts("Box built! Spawning resources...");
                    SpawnResourceInBox(storageContainer);
                }
            }
        }

        private void SpawnResourceInBox(StorageContainer boxEntity)
        {
            if (boxEntity == null || boxEntity.IsDestroyed) return;

            var resourceItem = ItemManager.CreateByName("sulfur.ore", 10);
            if (resourceItem != null)
            {
                if (!resourceItem.MoveToContainer(boxEntity.inventory))
                {
                    resourceItem.Remove();
                    return;
                }

                boxEntity.SendNetworkUpdate();
            }

            UnityEngine.Debug.Log("BoxPlugin: Resource spawned in the box");
        }
    }
}

Приведенный выше код добавляет следующие функции:
1. Команда /box для создания и размещения уникального ящика.
2. Обработчик события OnItemDeployed, который вызывается при размещении предмета игроком. Если размещенный предмет - это ящик, вызывается функция SpawnResourceInBox, которая спавнит ресурсы в ящике.

Убедитесь, что вы установили и настроили окружение разработки для плагинов Rust, и добавьте этот код в свой плагин. Затем скомпилируйте плагин и разместите его на вашем сервере Rust.

Удачи! Если у вас возникнут дополнительные вопросы, не стесняйтесь задавать.
 
Конечно, я могу помочь с созданием плагина для сервера Rust.

Прежде всего, вам понадобится установить и настроить окружение разработки для плагинов Rust. Вы можете найти подробную информацию об этом на официальном сайте Oxide: https://umod.org/documentation/games/rust/getting-started

После этого вы можете приступить к созданию плагина. Ниже приведен пример кода, который добавляет команду /box для создания и размещения уникального ящика, а также спавнит ресурсы в этом ящике при размещении:

C#:
using System;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("BoxPlugin", "Bratura", "1.0.0")]
    [Description("Spawns resources in a box placed by a player")]
    public class BoxPlugin : RustPlugin
    {
        private const string Permission_Use = "boxplugin.use";

        private void Init()
        {
            permission.RegisterPermission(Permission_Use, this);
            AddCovalenceCommand("box", "CmdBox");
            Subscribe<Action<Deployer, BaseEntity>>(nameof(OnItemDeployed));
            Puts("BoxPlugin: Initialized");
        }

        private void CmdBox(IPlayer player, string command, string[] args)
        {
            if (!player.HasPermission(Permission_Use))
            {
                player.Reply("You don't have permission to use this command.");
                return;
            }

            var basePlayer = player.Object as BasePlayer;
            if (basePlayer != null)
            {
                var boxDefinition = ItemManager.FindItemDefinition("box.wooden.large");
                if (boxDefinition != null)
                {
                    var boxItem = ItemManager.CreateByItemID(boxDefinition.itemid, 1);
                    if (boxItem != null)
                    {
                        basePlayer.GiveItem(boxItem);
                    }
                }
            }

            Puts($"BoxPlugin: {player.Name} used /box command");
        }

        private void OnItemDeployed(Deployer deployer, BaseEntity deployedEntity)
        {
            var storageContainer = deployedEntity as StorageContainer;
            if (storageContainer == null) return;

            if (deployedEntity.PrefabName.Contains("box.wooden.large"))
            {
                Puts("Player placed a box");

                if (storageContainer != null)
                {
                    Puts("Box built! Spawning resources...");
                    SpawnResourceInBox(storageContainer);
                }
            }
        }

        private void SpawnResourceInBox(StorageContainer boxEntity)
        {
            if (boxEntity == null || boxEntity.IsDestroyed) return;

            var resourceItem = ItemManager.CreateByName("sulfur.ore", 10);
            if (resourceItem != null)
            {
                if (!resourceItem.MoveToContainer(boxEntity.inventory))
                {
                    resourceItem.Remove();
                    return;
                }

                boxEntity.SendNetworkUpdate();
            }

            UnityEngine.Debug.Log("BoxPlugin: Resource spawned in the box");
        }
    }
}

Приведенный выше код добавляет следующие функции:
1. Команда /box для создания и размещения уникального ящика.
2. Обработчик события OnItemDeployed, который вызывается при размещении предмета игроком. Если размещенный предмет - это ящик, вызывается функция SpawnResourceInBox, которая спавнит ресурсы в ящике.

Убедитесь, что вы установили и настроили окружение разработки для плагинов Rust, и добавьте этот код в свой плагин. Затем скомпилируйте плагин и разместите его на вашем сервере Rust.

Удачи! Если у вас возникнут дополнительные вопросы, не стесняйтесь задавать.
Error while compiling BoxPlugin: The non-generic method 'Plugin.Subscribe(string)' cannot be used with type arguments | Line: 22, Pos: 13
давай ботик , ошибку получил
 
Error while compiling BoxPlugin: The non-generic method 'Plugin.Subscribe(string)' cannot be used with type arguments | Line: 22, Pos: 13
давай ботик , ошибку получил
Очень извиняюсь за путаницу. В случае с Rust плагинами Oxide.Core.Libraries.Covalence не имеет обобщенного метода Subscribe. Вот исправленный код:

C#:
using System;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("BoxPlugin", "Bratura", "1.0.0")]
    [Description("Spawns resources in a box placed by a player")]
    public class BoxPlugin : RustPlugin
    {
        private const string Permission_Use = "boxplugin.use";

        private void Init()
        {
            permission.RegisterPermission(Permission_Use, this);
            AddCovalenceCommand("box", "CmdBox");
            Puts("BoxPlugin: Initialized");
        }

        private void CmdBox(IPlayer player, string command, string[] args)
        {
            if (!player.HasPermission(Permission_Use))
            {
                player.Reply("You don't have permission to use this command.");
                return;
            }

            var basePlayer = player.Object as BasePlayer;
            if (basePlayer != null)
            {
                var boxDefinition = ItemManager.FindItemDefinition("box.wooden.large");
                if (boxDefinition != null)
                {
                    var boxItem = ItemManager.CreateByItemID(boxDefinition.itemid, 1);
                    if (boxItem != null)
                    {
                        basePlayer.GiveItem(boxItem);
                    }
                }
            }

            Puts($"BoxPlugin: {player.Name} used /box command");
        }

        private void OnEntityBuilt(Planner planner, GameObject go)
        {
            var storageContainer = go.GetComponent<StorageContainer>();
            if (storageContainer == null) return;

            if (go.name.Contains("box.wooden.large"))
            {
                Puts("Player placed a box");

                if (storageContainer != null)
                {
                    Puts("Box built! Spawning resources...");
                    SpawnResourceInBox(storageContainer);
                }
            }
        }

        private void SpawnResourceInBox(StorageContainer boxEntity)
        {
            if (boxEntity == null || boxEntity.IsDestroyed) return;

            var resourceItem = ItemManager.CreateByName("sulfur.ore", 10);
            if (resourceItem != null)
            {
                if (!resourceItem.MoveToContainer(boxEntity.inventory))
                {
                    resourceItem.Remove();
                    return;
                }

                boxEntity.SendNetworkUpdate();
            }

            UnityEngine.Debug.Log("BoxPlugin: Resource spawned in the box");
        }
    }
}

Добавленный код заменяет метод OnItemDeployed на OnEntityBuilt, что является событием вызывающимся при постройке объекта игроком. Подробнее об этом событии можно прочитать в официальной документации Oxide: https://umod.org/documentation/games/rust/events

Пожалуйста, попробуйте скомпилировать исправленный код. Если возникнут еще вопросы, с удовольствием помогу!
 
Очень извиняюсь за путаницу. В случае с Rust плагинами Oxide.Core.Libraries.Covalence не имеет обобщенного метода Subscribe. Вот исправленный код:

C#:
using System;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("BoxPlugin", "Bratura", "1.0.0")]
    [Description("Spawns resources in a box placed by a player")]
    public class BoxPlugin : RustPlugin
    {
        private const string Permission_Use = "boxplugin.use";

        private void Init()
        {
            permission.RegisterPermission(Permission_Use, this);
            AddCovalenceCommand("box", "CmdBox");
            Puts("BoxPlugin: Initialized");
        }

        private void CmdBox(IPlayer player, string command, string[] args)
        {
            if (!player.HasPermission(Permission_Use))
            {
                player.Reply("You don't have permission to use this command.");
                return;
            }

            var basePlayer = player.Object as BasePlayer;
            if (basePlayer != null)
            {
                var boxDefinition = ItemManager.FindItemDefinition("box.wooden.large");
                if (boxDefinition != null)
                {
                    var boxItem = ItemManager.CreateByItemID(boxDefinition.itemid, 1);
                    if (boxItem != null)
                    {
                        basePlayer.GiveItem(boxItem);
                    }
                }
            }

            Puts($"BoxPlugin: {player.Name} used /box command");
        }

        private void OnEntityBuilt(Planner planner, GameObject go)
        {
            var storageContainer = go.GetComponent<StorageContainer>();
            if (storageContainer == null) return;

            if (go.name.Contains("box.wooden.large"))
            {
                Puts("Player placed a box");

                if (storageContainer != null)
                {
                    Puts("Box built! Spawning resources...");
                    SpawnResourceInBox(storageContainer);
                }
            }
        }

        private void SpawnResourceInBox(StorageContainer boxEntity)
        {
            if (boxEntity == null || boxEntity.IsDestroyed) return;

            var resourceItem = ItemManager.CreateByName("sulfur.ore", 10);
            if (resourceItem != null)
            {
                if (!resourceItem.MoveToContainer(boxEntity.inventory))
                {
                    resourceItem.Remove();
                    return;
                }

                boxEntity.SendNetworkUpdate();
            }

            UnityEngine.Debug.Log("BoxPlugin: Resource spawned in the box");
        }
    }
}

Добавленный код заменяет метод OnItemDeployed на OnEntityBuilt, что является событием вызывающимся при постройке объекта игроком. Подробнее об этом событии можно прочитать в официальной документации Oxide: https://umod.org/documentation/games/rust/events

Пожалуйста, попробуйте скомпилировать исправленный код. Если возникнут еще вопросы, с удовольствием помогу!
можешь сделать, чтобы ресурсы спавнились каждые 5 секунд, у ящика был skinId и ресурсы спавнились только в этом ящике, не в каком другом!
 
можешь сделать, чтобы ресурсы спавнились каждые 5 секунд, у ящика был skinId и ресурсы спавнились только в этом ящике, не в каком другом!
добавь скин, и проверку на этот скин при спавне ресурсов. бинго!
 
Активность
Пока никто не печатает сообщение

Похожие темы