using UnityEngine; namespace Oxide.Plugins { [Info("GeneticPlanters", "Marte6",…
- User
using UnityEngine;
namespace Oxide.Plugins { [Info("GeneticPlanters", "Marte6", "1.0.0")] [Description("GeneticPlanters")] public class GeneticPlanters : RustPlugin { private static GeneticPlanters _pluginInstance;
private void OnEntityBuilt(Planner planner, GameObject gameObject) { if (planner == null || gameObject == null) { return; } BasePlayer player = planner.GetOwnerPlayer(); if (player == null) { return; } Item activeItem = player.GetActiveItem(); if (activeItem == null) { return; } if (gameObject.ToBaseEntity() is GrowableEntity growable) { NextTick(() => { if (growable.GetPlanter() != null) { growable.ChangeState(PlantProperties.State.Ripe, false); } }); } } }}
- Assistant
The
GeneticPlantersplugin for Rust, developed using Oxide, aims to modify the growth state of plants upon their placement in the game world. Here’s a breakdown of how the plugin functions:-
Namespace and Class Declaration: The plugin is defined within the
Oxide.Pluginsnamespace and the main classGeneticPlantersinherits fromRustPlugin, which provides basic functionalities needed for Rust game plugins. -
Plugin Attributes: The plugin uses two attributes,
[Info]and[Description], which provide metadata such as the plugin’s name, author, and version. -
Static Instance: A static instance of the plugin (
_pluginInstance) is declared, which might be used to access or modify the state throughout the plugin dynamically, though it’s unused explicitly in the provided snippet. -
Main Logic –
OnEntityBuilt:- This method is invoked when an entity is built in the game.
- It checks for null references to ensure that both
plannerandgameObjectare valid. Similarly, it retrieves the player and the item they are using, returning early if these are null. - The core functionality is focused on determining if the constructed entity is a
GrowableEntity(a plantable object). - Using the
NextTick()method ensures that changes to the entity are performed safely in the next server tick, which is important for thread safety and game stability. - If the plant is indeed in a planter (
growable.GetPlanter() != null), it changes the plant’s state toRipe, effectively fast-tracking its growth cycle without altering any other growth parameters or requiring manual intervention by the player.
Overall, the
GeneticPlantersplugin provides a straightforward mechanism to automatically change the growth status of plants placed in planters, potentially for convenience or gameplay balancing. -
- User
using System; using UnityEngine;
[CreateAssetMenu(menuName = "Rust/Plant Properties")] public class PlantProperties : ScriptableObject { public enum State { Seed, Seedling, Sapling, Crossbreed, Mature, Fruiting, Ripe, Dying }
[Serializable] public struct Stage { public State nextState; public float lifeLength; public float health; public float resources; public float yield; public GameObjectRef skinObject; public bool IgnoreConditions; public float lifeLengthSeconds => lifeLength * 60f; } public Translate.Phrase Description; public GrowableGeneProperties Genes; [ArrayIndexIsEnum(enumType = typeof(State))] public Stage[] stages = new Stage[8]; [Header("Metabolism")] public AnimationCurve timeOfDayHappiness = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(12f, 1f), new Keyframe(24f, 0f)); public AnimationCurve temperatureHappiness = new AnimationCurve(new Keyframe(-10f, -1f), new Keyframe(1f, 0f), new Keyframe(30f, 1f), new Keyframe(50f, 0f), new Keyframe(80f, -1f)); public AnimationCurve temperatureWaterRequirementMultiplier = new AnimationCurve(new Keyframe(-10f, 1f), new Keyframe(0f, 1f), new Keyframe(30f, 1f), new Keyframe(50f, 1f), new Keyframe(80f, 1f)); public AnimationCurve fruitVisualScaleCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.75f, 1f), new Keyframe(1f, 0f)); public int MaxSeasons = 1; public float WaterIntake = 20f; public float OptimalLightQuality = 1f; public float OptimalWaterQuality = 1f; public float OptimalGroundQuality = 1f; public float OptimalTemperatureQuality = 1f; [Header("Harvesting")] public BaseEntity.Menu.Option pickOption; public BaseEntity.Menu.Option pickAllOption; public BaseEntity.Menu.Option eatOption; public ItemDefinition pickupItem; public BaseEntity.Menu.Option cloneOption; public BaseEntity.Menu.Option cloneAllOption; public BaseEntity.Menu.Option removeDyingOption; public BaseEntity.Menu.Option removeDyingAllOption; public ItemDefinition removeDyingItem; public GameObjectRef removeDyingEffect; public int pickupMultiplier = 1; public GameObjectRef pickEffect; public int maxHarvests = 1; public bool disappearAfterHarvest; [Header("Seeds")] public GameObjectRef CrossBreedEffect; public ItemDefinition SeedItem; public ItemDefinition CloneItem; public int BaseCloneCount = 1; [Header("Market")] public int BaseMarketValue = 10;}
- Assistant
The
PlantPropertiesscript defines aScriptableObjectin Unity for managing various properties and behaviors of plants within a game, likely for a setting similar to Rust. Here's a breakdown of the key components:Structure
-
Enum
State:- Represents the different growth stages of a plant, ranging from
SeedtoDying. - Defines a lifecycle from beginning (
Seed) to end (Dying), which the plant progresses through.
- Represents the different growth stages of a plant, ranging from
-
Struct
Stage:- Represents a specific stage in the plant's lifecycle.
- Contains several properties:
nextState: The subsequent state in the lifecycle.lifeLength: Duration of the stage, expressed in an unspecified unit.health,resources,yield: Attributes that influence the plant's performance.skinObject: Visual representation of the plant at this stage.IgnoreConditions: Determines if the plant's growth is unaffected by environmental conditions.lifeLengthSeconds: ConvertslifeLengthinto seconds by multiplying it by 60.
-
Fields and Properties:
stages: An array ofStagestructures representing each growth phase.timeOfDayHappiness,temperatureHappiness,temperatureWaterRequirementMultiplier,fruitVisualScaleCurve: Animation curves that dictate plant performance relative to time of day, temperature, water needs, and visual scale of fruiting stages.MaxSeasons,WaterIntake,OptimalLightQuality, etc.: Parameters defining ideal conditions for plant growth and maintenance.
-
Harvesting Options:
- Includes various menu options (
pickOption,eatOption, etc.) allowing player interactions such as picking, eating, or cloning plants. pickupItem,removeDyingItem: Define what items are acquired through certain interactions.pickEffect,removeDyingEffect: Visual or audio effects associated with actions like harvesting or removing dying plants.
- Includes various menu options (
-
Seed and Clone Management:
- Defines items related to seeds and cloning (
SeedItem,CloneItem), as well as effects and behavior associated with crossbreeding and cloning (e.g.,CrossBreedEffect).
- Defines items related to seeds and cloning (
-
Market Value:
BaseMarketValue: The default market valuation of the plant, potentially contributing to trading or economic dynamics within the game.
Usage
CreateAssetMenu: This attribute allows the creation of a newPlantPropertiesasset through Unity’s Asset menu, facilitating the process of defining plant properties in the editor.- ScriptableObject:
- An efficient way to manage large data sets within Unity, separating data from logic. This setup makes it easy to tweak plant characteristics without altering the game's core code base.
Overall,
PlantPropertiesprovides a comprehensive template for specifying and adjusting various aspects of plant growth, interaction, and economic value in a game environment. It can be extended or customized to meet specific gameplay requirements. -
- User
using System; using UnityEngine;
[CreateAssetMenu(menuName = "Rust/Growable Gene Properties")] public class GrowableGeneProperties : ScriptableObject { [Serializable] public struct GeneWeight { public float BaseWeight;
public float[] SlotWeights; public float CrossBreedingWeight; } [ArrayIndexIsEnum(enumType = typeof(GrowableGenetics.GeneType))] public GeneWeight[] Weights = new GeneWeight[5];}
- Assistant
The
GrowableGenePropertiesclass defines aScriptableObjectin Unity designed to manage genetic characteristics of growable plants in a game, likely within a context similar to Rust. This class focuses on how different genetic traits influence plant growth through weighting parameters. Here's a detailed look at its structure and purpose:Structure
-
GeneWeightStruct:- An inner structure to define weights associated with different genetic attributes.
- Fields:
BaseWeight: Defines the fundamental influence of a genetic trait without any modifications or interactions with other traits.SlotWeights: An array of weights, presumably associating additional influences based on specific slots or contexts. This allows for more granular control over how each gene affects the plant.CrossBreedingWeight: Represents the influence a genetic trait has during crossbreeding, affecting the probability or outcome when genes from different plants combine.
-
Weights Array:
- An array of
GeneWeightstructures that correspond to genetic traits defined in theGrowableGenetics.GeneTypeenumeration. - Attributes:
ArrayIndexIsEnum: This decorator ensures that each entry in theWeightsarray corresponds to a specific gene type defined by an enumeration. This approach aids in maintaining consistency and clarity in designing and managing genetic properties.
- An array of
Usage
CreateAssetMenu: This attribute enables users to create instances ofGrowableGenePropertiesdirectly from the Unity Editor's asset menu, facilitating the management of genetic data.- ScriptableObject:
- The use of
ScriptableObjectis an efficient approach to handling game data, especially when the data structure is complex or includes various configurations like genetics. It allows for easy adjustment and experimentation without requiring code changes.
- The use of
Context and Integration
This class is likely integrated with a larger system that manages plant growth, genetics, and possibly crossbreeding mechanics:
- GrowableGenetics.GeneType: This enumeration, presumably defined elsewhere, categorizes the possible gene types that plants can have. Examples might include growth rate, yield, resistance, etc.
- Genetic Management: By adjusting the weights in each
GeneWeightinstance, developers or designers can fine-tune how each gene impacts the plant's phenotypical outcomes, allowing for a dynamic and varied plant breeding system.
Overall,
GrowableGenePropertiesprovides a structured approach to managing genetic variables in a game, empowering developers to simulate complex genetics-based growth systems with adaptability and ease. -
- User
using System; using System.Collections.Generic; using Facepunch;
public static class GrowableGenetics { public enum GeneType { Empty, WaterRequirement, GrowthSpeed, Yield, Hardiness }
public struct GeneWeighting { public float Weighting; public GeneType GeneType; } public const int GeneSlotCount = 6; public const float CrossBreedingRadius = 1.5f; private static GeneWeighting[] neighbourWeights = new GeneWeighting[Enum.GetValues(typeof(GeneType)).Length]; private static GeneWeighting dominant = default(GeneWeighting); public static void CrossBreed(GrowableEntity growable) { List<GrowableEntity> list = Pool.Get<List<GrowableEntity>>(); Vis.Entities(growable.transform.position, 1.5f, list, 524288); bool flag = false; for (int i = 0; i < 6; i++) { GrowableGene growableGene = growable.Genes.Genes[i]; GeneWeighting dominantGeneWeighting = GetDominantGeneWeighting(growable, list, i); if (dominantGeneWeighting.Weighting > growable.Properties.Genes.Weights[(int)growableGene.Type].CrossBreedingWeight) { flag = true; growableGene.Set(dominantGeneWeighting.GeneType); } } if (flag) { growable.SendNetworkUpdate(); } } private static GeneWeighting GetDominantGeneWeighting(GrowableEntity crossBreedingGrowable, List<GrowableEntity> neighbours, int slot) { PlanterBox planter = crossBreedingGrowable.GetPlanter(); if (planter == null) { dominant.Weighting = -1f; return dominant; } for (int i = 0; i < neighbourWeights.Length; i++) { neighbourWeights[i].Weighting = 0f; neighbourWeights[i].GeneType = (GeneType)i; } dominant.Weighting = 0f; foreach (GrowableEntity neighbour in neighbours) { if (!neighbour.isServer) { continue; } PlanterBox planter2 = neighbour.GetPlanter(); if (!(planter2 == null) && !(planter2 != planter) && !(neighbour == crossBreedingGrowable) && neighbour.prefabID == crossBreedingGrowable.prefabID && !neighbour.IsDead()) { GeneType type = neighbour.Genes.Genes[slot].Type; float crossBreedingWeight = neighbour.Properties.Genes.Weights[(int)type].CrossBreedingWeight; float num = (neighbourWeights[(int)type].Weighting += crossBreedingWeight); if (num > dominant.Weighting) { dominant.Weighting = num; dominant.GeneType = type; } } } return dominant; }}
- Assistant
The
GrowableGeneticsclass provides a framework for managing genetics and crossbreeding of plants, likely within a game similar to Rust, using a static utility class. This class focuses on the process of crossbreeding plants through genetic dominance. Here’s a key breakdown of the components and their functions:Components
-
GeneTypeEnum:- Defines various genetic traits that a plant can possess, such as
Empty,WaterRequirement,GrowthSpeed,Yield, andHardiness. - Each trait potentially influences a plant's characteristics such as resilience, production rate, and resource needs.
- Defines various genetic traits that a plant can possess, such as
-
GeneWeightingStruct:- Represents the influence magnitude (
Weighting) for a specificGeneType. - Used to determine which gene type becomes dominant during crossbreeding.
- Represents the influence magnitude (
-
Constants:
GeneSlotCount: Indicates the number of gene slots available, set to 6, implying each plant can hold six genetic attributes.CrossBreedingRadius: Determines the spatial radius within which crossbreeding effects can occur.
-
Static Fields:
- An array
neighbourWeightsto store the cumulative weighting for each gene type when assessing nearby plants. - A
dominantgene weighting to identify the prevailing gene type during the crossbreeding process.
- An array
Main Methods
-
CrossBreedMethod:- Facilitates the crossbreeding process by examining neighboring plants and determining gene dominance for a
GrowableEntity(a game object eligible for growth and breeding). - Utilizes the
Vis.Entitiescall, a functionality typical in Rust's engine to gather nearby entities within a specific radius (CrossBreedingRadius). - For each gene slot, it calculates the most dominant gene type among neighboring plants using
GetDominantGeneWeighting. - If any gene slot changes as a result of crossbreeding, it sends a network update to reflect those changes to other clients.
- Facilitates the crossbreeding process by examining neighboring plants and determining gene dominance for a
-
GetDominantGeneWeightingMethod:- Identifies the dominant gene type for a specific slot of a
GrowableEntityby assessing gene weightings from surrounding entities. - Ensures that crossbreeding only occurs between plants in the same
PlanterBoxand that they are not dead and share the same prefab ID as the plant being crossbred. - Tallies the weightings from all neighbors' genes to determine which gene type dominates, updating the
dominantgene weighting accordingly.
- Identifies the dominant gene type for a specific slot of a
Usage and Integration
This system integrates genetic management with environmental interactions:
- Crossbreeding Mechanics: The code enables plants to inherit attributes from proximal plants, adding variability and complexity to the game’s plant growth mechanics.
- PlanterBox: Ensures genetic mixing only between plants sharing the same planter, grounding the crossbreeding process to spatial and gameplay logic (e.g., no crossbreeding between plants in different planters).
Overall, this code emphasizes natural selection through dominant gene traits, fostering realism and unpredictability in the growth and breeding of game plants. It seamlessly merges spatial considerations and genetic rules, providing users with an immersive in-game breeding system.
-
- User
quero fazer o meuplugin GeneticPlanters, trocar o genes da planta para GGGYYY
- Assistant
Para alterar os genes de uma planta para um padrão específico como "GGGYYY" ao usar o plugin
GeneticPlanters, você precisará modificar o métodoOnEntityBuiltno plugin para definir explicitamente os genes de cada planta após ela ser criada. Abaixo está um exemplo de como você pode implementar isso:using UnityEngine; namespace Oxide.Plugins { [Info("GeneticPlanters", "Marte6", "1.1.0")] [Description("Modifica os genes das plantas para um padrão específico ao serem plantadas.")] public class GeneticPlanters : RustPlugin { private void OnEntityBuilt(Planner planner, GameObject gameObject) { if (planner == null || gameObject == null) { return; } BasePlayer player = planner.GetOwnerPlayer(); if (player == null) { return; } Item activeItem = player.GetActiveItem(); if (activeItem == null) { return; } if (gameObject.ToBaseEntity() is GrowableEntity growable) { NextTick(() => { if (growable.GetPlanter() != null) { SetGenesToGGGYYY(growable); growable.ChangeState(PlantProperties.State.Ripe, false); } }); } } private void SetGenesToGGGYYY(GrowableEntity growable) { if (growable == null || growable.Genes == null || growable.Genes.Genes.Length < 6) { PrintError("A planta ou seus genes não estão corretamente inicializados."); return; } // Set genes to the pattern GGGYYY growable.Genes.Genes[0].Set(GrowableGenetics.GeneType.GrowthSpeed); growable.Genes.Genes[1].Set(GrowableGenetics.GeneType.GrowthSpeed); growable.Genes.Genes[2].Set(GrowableGenetics.GeneType.GrowthSpeed); growable.Genes.Genes[3].Set(GrowableGenetics.GeneType.Yield); growable.Genes.Genes[4].Set(GrowableGenetics.GeneType.Yield); growable.Genes.Genes[5].Set(GrowableGenetics.GeneType.Yield); growable.SendNetworkUpdate(); } } }Explicação do Código
-
Verificações Iniciais:
- O método
OnEntityBuiltcertifica-se de que tanto o planejador quanto o objeto de jogo são válidos antes de continuar. - Confirma que o jogador e o item ativo também são não nulos para evitar erros.
- O método
-
Identificando a Entidade Cultivável (GrowableEntity):
- Após a confirmação, verifica se a entidade construída é uma
GrowableEntity. - Em seguida, no próximo tick (usando
NextTick), modifica os genes da planta para o padrão desejado se ela estiver em um plantador.
- Após a confirmação, verifica se a entidade construída é uma
-
Método SetGenesToGGGYYY:
- Modifica os genes da planta para ficar com os primeiros três slots como
GrowthSpeed(crescimento) e os últimos três comoYield(rendimento). - Após a alteração, envia uma atualização de rede para sincronizar o estado alterado com outros jogadores (usando
SendNetworkUpdate).
- Modifica os genes da planta para ficar com os primeiros três slots como
Ao implementar essa mudança, sempre certifique-se de que está testando em um ambiente seguro para garantir que as alterações funcionem conforme esperado e não causem instabilidades no servidor.
-