este código está funcionando perfeitamente, não altere como ele funciona, só tente otimizar e melhorar as nomenclaturas, remova comentários tbm:
using System;
using System.Collections.Generic;
using System.Linq;
using Facepunch;
using Newtonsoft.Json;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
Esse erro ocorre porque você está tentando passar um valor nulo potencial para um método que espera um valor não nulo (Vector3, que é um tipo de valor e não pode ser nulo). O operador de "null-conditional" (?.) retorna null se qualquer parte da expressão anterior for null, o que não é compatível com os métodos Drop que esperam parâmetros do tipo Vector3.
Você pode corrigir isso verificando se player não é null antes de chamar o método Drop. Aqui está uma maneira de ajustar seu código:
csharp
private void MoveOrDropItem(Item item, ItemContainer container, BasePlayer player, bool moveToInventory)
{
if (moveToInventory && !item.MoveToContainer(container))
{
if (player != null)
{
var dropPosition = player.GetCenter();
var dropVelocity = player.GetDropVelocity();
item.Drop(dropPosition, dropVelocity);
}
}
}
Neste ajuste, o código primeiro verifica se player não é null antes de tentar obter o centro e a velocidade de queda do player. Isso garante que os métodos GetCenter() e GetDropVelocity() sejam chamados somente quando player não for null, eliminando o erro de conversão.
User
Argument 1: cannot convert from 'UnityEngine.Vector3?' to 'UnityEngine.Vector3'CS1503
private void ProduceScrap(Item item, int itemAmount, ItemContainer container, BasePlayer player, bool moveToInventory, float efficiency)
{
int scrapAmount = Mathf.Max((int)(_configData.ScrapRatio * item.info.Blueprint.scrapFromRecycle * itemAmount), 1);
code
Item newScrap = ItemManager.CreateByName("scrap", scrapAmount);
if (!moveToInventory)
newScrap.SetFlag(ItemScrapedFlag, true);
if (!newScrap.MoveToContainer(container))
{
newScrap.Drop(player?.GetCenter(), player?.GetDropVelocity());
}
}
Assistant
Você está enfrentando o mesmo problema de tentar passar um valor nulo potencial (resultado da expressão player?.GetCenter()) para um método que espera um valor não nulo (Vector3). Para corrigir isso, você deve garantir que as chamadas aos métodos GetCenter() e GetDropVelocity() só sejam feitas se player não for nulo. Aqui está como você pode ajustar o método ProduceScrap para resolver esse problema:
csharp
private void ProduceScrap(Item item, int itemAmount, ItemContainer container, BasePlayer player, bool moveToInventory, float efficiency)
{
int scrapAmount = Mathf.Max((int)(_configData.ScrapRatio * item.info.Blueprint.scrapFromRecycle * itemAmount), 1);
Item newScrap = ItemManager.CreateByName("scrap", scrapAmount);
if (!moveToInventory)
{
newScrap.SetFlag(ItemScrapedFlag, true);
}
if (!newScrap.MoveToContainer(container))
{
if (player != null)
{
var dropPosition = player.GetCenter();
var dropVelocity = player.GetDropVelocity();
newScrap.Drop(dropPosition, dropVelocity);
}
}
}
Neste ajuste, o método primeiro verifica se player é não nulo antes de chamar GetCenter() e GetDropVelocity(). Isso garante que você não está tentando passar um valor null para um método que espera um Vector3.
User
Argument 1: cannot convert from 'UnityEngine.Vector3?' to 'UnityEngine.Vector3'CS1503
private void ProduceIngredients(Item item, int itemAmount, ItemContainer container, bool moveToInventory, BasePlayer player, float efficiency)
{
foreach (ItemAmount ingredient in item.info.Blueprint.ingredients)
{
if (ingredient.itemDef.shortname == "scrap")
continue;
code
int ingredientsToProduce = (int)(itemAmount * efficiency * ingredient.amount / item.info.Blueprint.amountToCreate);
ingredientsToProduce = Mathf.Max(Mathf.CeilToInt(UnityEngine.Random.Range(0f, 1f) > 0.5f ? ingredientsToProduce : 1), 1);
for (int i = 0; i < ingredientsToProduce; i += ingredient.itemDef.stackable)
{
int toCreate = Mathf.Min(ingredientsToProduce - i, ingredient.itemDef.stackable);
try
{
Item newIngredient = ItemManager.Create(ingredient.itemDef, toCreate);
if (!moveToInventory)
newIngredient.SetFlag(ItemScrapedFlag, true);
if (!newIngredient.MoveToContainer(container))
{
newIngredient.Drop(player?.GetCenter(), player?.GetDropVelocity());
}
}
catch
{
Puts($"Error recycling {item.info.shortname} to {ingredient.itemDef.shortname}");
}
}
}
}
Assistant
O problema que está ocorrendo é que você está usando operadores de nulidade (?.) em locais onde eles não são apropriados. Os métodos GetCenter() e GetDropVelocity() retornam valores do tipo Vector3, que não podem ser nulos. Quando você utiliza ?., o resultado pode ser um valor nulo (Vector3?), o que não é compatível com os parâmetros do método Drop, que espera um Vector3.
Para corrigir esse problema, você precisará garantir que somente tente obter o centro e a velocidade do jogador quando o objeto player não for nulo. Aqui está como você pode ajustar o método ProduceIngredients:
csharp
private void ProduceIngredients(Item item, int itemAmount, ItemContainer container, bool moveToInventory, BasePlayer player, float efficiency)
{
foreach (ItemAmount ingredient in item.info.Blueprint.ingredients)
{
if (ingredient.itemDef.shortname == "scrap")
continue;
int ingredientsToProduce = (int)(itemAmount * efficiency * ingredient.amount / item.info.Blueprint.amountToCreate);
ingredientsToProduce = Mathf.Max(Mathf.CeilToInt(UnityEngine.Random.Range(0f, 1f) > 0.5f ? ingredientsToProduce : 1), 1);
for (int i = 0; i < ingredientsToProduce; i += ingredient.itemDef.stackable)
{
int toCreate = Mathf.Min(ingredientsToProduce - i, ingredient.itemDef.stackable);
try
{
Item newIngredient = ItemManager.Create(ingredient.itemDef, toCreate);
if (!moveToInventory)
newIngredient.SetFlag(ItemScrapedFlag, true);
if (!newIngredient.MoveToContainer(container) && player != null)
{
Vector3 dropPosition = player.GetCenter();
Vector3 dropVelocity = player.GetDropVelocity();
newIngredient.Drop(dropPosition, dropVelocity);
}
}
catch
{
Puts($"Error recycling {item.info.shortname} to {ingredient.itemDef.shortname}");
}
}
}
}
Este ajuste inclui uma verificação para garantir que o player não é nulo antes de tentar acessar métodos que retornam Vector3, evitando assim a tentativa de passar valores nulos para o método Drop, o que deve eliminar o erro de compilação que você está enfrentando.
User
The non-generic method 'BaseNetworkable.GetParentEntity()' cannot be used with type argumentsCS0308
private bool CanPlayerOpenRecycler(BasePlayer player)
{
if (
player == null
|| !(
player.IsAlive()
&& !player.IsWounded()
&& player.CanBuild()
&& player.IsOnGround()
&& !player.IsFlying
&& !player.isInAir
&& !player.isMounted
&& player.GetParentEntity() == null
&& !player.IsSwimming()
&& player.GetComponentInParent() == null
&& player.GetComponentInParent() == null
&& player.GetComponentInParent() == null
)
)
{
player.ChatMessage(lang.GetMessage("RecyclingDenied", this, player.UserIDString));
return false;
}
code
return true;
}
Assistant
O erro que você está recebendo ocorre porque o método GetParentEntity() não é genérico, portanto, tentar usá-lo com um argumento de tipo (<BaseMountable>) não é permitido. Você deve usar GetParentEntity() sem qualquer tipo genérico e fazer manualmente a verificação de tipo. Aqui está como você pode corrigir isso:
Neste ajuste, usei player.GetParentEntity() is not BaseMountable para verificar se a entidade pai do jogador não é do tipo BaseMountable, o que mantém o intuito original do código. Essa abordagem garante que estamos usando o método GetParentEntity() corretamente sem tentar aplicar argumentos de tipo que não são suportados.
User
volte com as mensagens de erro que tinham antes
Assistant
Para adicionar novamente as mensagens de erro específicas e descritivas que você tinha anteriormente, você precisa ajustar o método CanPlayerOpenRecycler para fornecer mensagens de erro específicas para cada caso de falha. Veja como isso pode ser feito:
Nesta versão do método, verifiquei cada condição separadamente, enviando uma mensagem apropriada ao jogador quando alguma das condições previstas bloqueia a ação de abrir o reciclador. Cada chamada de player.ChatMessage é feita imediatamente antes do return false, assim, o jogador é informado especificamente sobre a razão pela qual não pode abrir o reciclador. O operador de condicional nulo (?.) é usado apenas nas mensagens onde player pode ser null.