manojl
November 15, 2019, 12:39am
1
Can someone help me with Reload by keypress R …
I hit R and nothing happens, neither a mistake nor anything …
My srcipt
(Line 341+)
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UltimateSurvival.GUISystem;
namespace UltimateSurvival
{
public class AmmoDragHandler : MonoSingleton<ItemDragHandler>
{
//Define properties for a gun
// Definir propriedades para uma arma
protected ItemProperty.Value m_AmmoProperty;
protected ItemProperty.Value m_AmmoCapacity;
protected ItemProperty.Value m_AmmoAmount;
[HideInInspector]
public int m_NeedAmmo = 0;
[HideInInspector]
public int m_AmmoStack = 0;
[HideInInspector]
public bool m_singleLoad = false;
[HideInInspector]
public SavableItem m_itemUnderPointer;
//get the main iteminspector
// pega o iteminspector principal
private ItemDragHandler itemDragHandler;
//Audio for reload
// Áudio para recarregar
[SerializeField]
[Tooltip("Sounds that will play when trying to reload")]
private SoundPlayer m_ReloadAudio;
//new variables for reload by key press>>
// novas variáveis para recarregar pressionando a tecla >>
private PlayerEventHandler m_PlayerEventHandler;
//[SerializeField] for getting the main inventory
// [SerializeField] para obter o inventário principal
[SerializeField]
private GameObject m_Inventory;
private ItemContainer getInventory;
private void Start()
{
itemDragHandler = transform.GetComponentInParent<ItemDragHandler>();
//get the component for the playereventhandler >>
// obtém o componente para o playereventhandler >>
m_PlayerEventHandler = transform.parent.GetComponentInParent<PlayerEventHandler>();
//only if the gameObject is set and has a value >>
// apenas se o gameObject estiver definido e tiver um valor >>
if (m_Inventory)
//get the itemContainer component from the main inventory gameObject
// obtém o componente itemContainer do jogo principal de inventárioObject
getInventory = m_Inventory.GetComponent<ItemContainer>();
}
//loadAmmo
public bool LoadAmmo(Slot initialSlot, SavableItem itemUnderPointer, SavableItem m_DraggedItem)
{
bool canLoadAmmo = (
//make sure that both the dragged item and the item in the slot exist
// verifique se o item arrastado e o item no slot existem
itemUnderPointer && m_DraggedItem &&
//make sure that both items have the property ammo type, so you dont get null values
// verifique se os dois itens possuem o tipo de munição da propriedade, para que você não obtenha valores nulos
m_DraggedItem.HasProperty ("Ammo Type") && itemUnderPointer.HasProperty ("Ammo Type") &&
//make sure that both the ammo and the weapon have the same ammo type
// verifique se a munição e a arma têm o mesmo tipo de munição
m_DraggedItem.GetPropertyValue ("Ammo Type").String == itemUnderPointer.GetPropertyValue ("Ammo Type").String &&
//make sure only the dragged item is ammo and not the item already in the slot
// verifique se apenas o item arrastado é munição e não o item que já está no slot
m_DraggedItem.HasProperty ("Is Ammo") &&
!itemUnderPointer.HasProperty ("Is Ammo") &&
itemUnderPointer.HasProperty ("Ammo Capacity") && itemUnderPointer.HasProperty ("Ammo")
);
// if bullets are being dropped on the correct ammo magazine
// se as balas estiverem sendo lançadas na revista de munição correta
bool canLoadAmmoMag = (
//make sure that both the dragged item and the item in the slot exist
// verifique se o item arrastado e o item no slot existem
itemUnderPointer && m_DraggedItem &&
//make sure that both items have the property ammo type, so you dont get null values
// verifique se os dois itens possuem o tipo de munição da propriedade, para que você não obtenha valores nulos
m_DraggedItem.HasProperty ("Ammo Type") && itemUnderPointer.HasProperty ("Ammo Type") &&
//make sute that both the ammo and the weapon have the same ammo type
// verifique se a munição e a arma têm o mesmo tipo de munição
m_DraggedItem.GetPropertyValue ("Ammo Type").String == itemUnderPointer.GetPropertyValue ("Ammo Type").String &&
//make sure both the dragged item is ammo the item already in the slot
// verifique se o item arrastado é munição e o item já está no slot
m_DraggedItem.HasProperty ("Is Ammo") &&
itemUnderPointer.HasProperty ("Is Ammo Mag") &&
!m_DraggedItem.HasProperty ("Is Ammo Mag")
);
//if the weapon requires an ammo magazine
// se a arma exigir uma revista de munição
bool requiresMag = (
canLoadAmmo &&
itemUnderPointer.HasProperty("Requires Ammo Mag") &&
!itemUnderPointer.HasProperty ("Is Ammo Mag")
);
//the item being dragged is an ammo magazine on to a compatible weapon
// o item que está sendo arrastado é uma revista de munição para uma arma compatível
bool loadFromAmmoMag = (
requiresMag && !canLoadAmmoMag
);
//load the ammo magazine
// carrega o magazine de munição
if (canLoadAmmoMag) {
//picked up ammo stack size
// pegou o tamanho da pilha de munição
int ammoStack = m_DraggedItem.CurrentInStack;
//current ammo
// munição atual
m_AmmoAmount = itemUnderPointer.GetPropertyValue ("Ammo");
var ammo = m_AmmoAmount.Int;
//capacity
//capacidade
m_AmmoCapacity = itemUnderPointer.GetPropertyValue ("Ammo Capacity");
ammo.Current += ammoStack; //has to be correct type // deve ser do tipo correto
//load the ammo in to the magazine
// carrega a munição no magazine
if (ammoStack > 0)
{
return loadAmmoItem(itemUnderPointer, m_DraggedItem, ammoStack, initialSlot, false, true);
}
else
{
return false;
}
} else if (canLoadAmmo)
{
//define our variable
//picked up ammo stack size
// define nossa variável
// pegou o tamanho da pilha de munição
int ammoStack = m_DraggedItem.CurrentInStack;
//current ammo // munição atual
if (ammoStack > 0){
// can only load magazinese in to a weapon make sure weapon has property fo has ammo mag
// só pode carregar magazinês em uma arma para garantir que a arma tenha propriedades para a munição
if (loadFromAmmoMag && itemUnderPointer.HasProperty ("Has Ammo Mag") && requiresMag)
{
//check that weapon doesnt already have nagazine inserted
// verifique se a arma ainda não tem um magazine inserido
if (!itemUnderPointer.GetPropertyValue ("Has Ammo Mag").Bool)
{
//get the ammo from the dragged magazine
// pegue a munição do magazine arrastada
if(m_DraggedItem.HasProperty("Is Ammo Mag"))
{
ammoStack = m_DraggedItem.GetPropertyValue ("Ammo").Int.Current;
}
else
{
return false;
}
//flag that the magazine has benn inserted into weapon
// sinaliza que a revista foi inserida na arma
var hasAmmo = itemUnderPointer.GetPropertyValue ("Has Ammo Mag");
hasAmmo.SetValue (ItemProperty.Type.Bool, true);
//load the magazine in to the weapon
// carrega a revista na arma
return loadAmmoItem (itemUnderPointer, m_DraggedItem, ammoStack, initialSlot, true, true);
}
else
{
return false;
}
//load the ammo directly in to the weapon
// carrega a munição diretamente na arma
}
else
{ if (!m_DraggedItem.HasProperty("Is Ammo Mag"))
{
return loadAmmoItem (itemUnderPointer, m_DraggedItem, ammoStack, initialSlot, true, false);
}
else
{
return false;
}
}
}
else
{
//item has no ammo to load
// o item não tem munição para carregar
itemDragHandler.PutItemBack (initialSlot);
initialSlot.Refresh ();
//make sure that the item is dragged
// certifique-se de que o item seja arrastado
if(itemDragHandler.m_DraggedItemRT)
{
//destroy the ammo object we dragged
// destrói o objeto de munição que arrastamos
Destroy(itemDragHandler.m_DraggedItemRT.gameObject);
itemDragHandler.m_DraggedItem = null;
itemDragHandler.m_Dragging = false;
}
return true;
}
}
else
{
return false;
}
}
//generic load ammo function - can be use for magazines or weapons
// função de munição de carga genérica - pode ser usada para revistas ou armas
public bool loadAmmoItem(SavableItem itemUnderPointer, SavableItem m_DraggedItem, int ammoStack, Slot initialSlot, bool animateLoad, bool singleLoad){
m_singleLoad = singleLoad;
m_itemUnderPointer = itemUnderPointer;
m_AmmoAmount = itemUnderPointer.GetPropertyValue ("Ammo");
//making sure that the equipped item is the same one that is dragged on to
// certificando-se de que o item equipado seja o mesmo que é arrastado para
if (itemUnderPointer != m_PlayerEventHandler.EquippedItem.Get())
animateLoad = false; //dont play the animation if its not the same item // não reproduz a animação se não for o mesmo item
var ammo = m_AmmoAmount.Int;
//capacity
//capacidade
m_AmmoCapacity = itemUnderPointer.GetPropertyValue ("Ammo Capacity");
//make sure that the gun is not already fully loaded
// verifique se a arma ainda não está totalmente carregada
if (m_AmmoAmount.Int.Current < m_AmmoCapacity.Int.Current) {
m_NeedAmmo = m_AmmoCapacity.Int.Current - m_AmmoAmount.Int.Current;
//if you need more ammo than what is in the entire stack, we consume all the ammo
// se você precisar de mais munição do que o que está na pilha inteira, consumimos toda a munição
if (m_NeedAmmo >= ammoStack) {
//reload the gun
// recarrega a arma
ammo.Current += ammoStack; //has to be correct type // deve ser do tipo correto
m_AmmoAmount.SetValue (ItemProperty.Type.Int, ammo);
m_AmmoStack = ammoStack;
//only animate if set to do so
// apenas animar se configurado para fazer isso
if (animateLoad)
{
GameController.LocalPlayer.Reload.Try (m_AmmoStack, m_singleLoad);
}
else
{
//make some noise when reloading magazines
// faz barulho ao recarregar revistas
m_ReloadAudio.Play2D ();
}
//make sure that the item is dragged
// certifique-se de que o item seja arrastado
if(itemDragHandler.m_DraggedItemRT)
{
//Destroy the ammo object
// Destrói o objeto de munição
Destroy (itemDragHandler.m_DraggedItemRT.gameObject);
itemDragHandler.m_DraggedItem = null;
itemDragHandler.m_Dragging = false;
initialSlot.Refresh ();
}
else
{
//set the slot with ammo to null as its being used up
// configura o slot com munição para null, pois está sendo usado
initialSlot.ItemHolder.SetItem (null);
}
return true;
}
//else we eill use all the ammo we can and return what is left
// caso contrário, usaremos toda a munição que pudermos e retornaremos o que resta
else
{
ammo.Current += m_NeedAmmo; //has to be correct type // deve ser do tipo correto
m_AmmoAmount.SetValue(ItemProperty.Type.Int, ammo);
m_AmmoStack = m_NeedAmmo;
int remainingAmmo = ammoStack - m_NeedAmmo;
m_DraggedItem.CurrentInStack = remainingAmmo;
//only animate if set to do so
// apenas animar se configurado para fazer isso
if (animateLoad)
{
GameController.LocalPlayer.Reload.Try (m_AmmoStack, m_singleLoad);
}
else
{
//make some noise when reloading magazines
// faz barulho ao recarregar magazines
m_ReloadAudio.Play2D ();
}
//make sure that the item is dragged
// certifique-se de que o item seja arrastado
if(itemDragHandler.m_DraggedItemRT)
{
//put whats left in our ammo stack back where we picked it up
// coloca o que resta na nossa pilha de munição de volta onde a pegamos
itemDragHandler.PutItemBack(initialSlot);
initialSlot.Refresh();
//destroy the ammo object dragged
// destrói o objeto de munição arrastado
Destroy (itemDragHandler.m_DraggedItemRT.gameObject);
itemDragHandler.m_DraggedItem = null;
itemDragHandler.m_Dragging = false;
}
return true;
}
}
else
{
return false;
}
}
void update(){
//get key input for when the 'R' Key us pressed and realesed
// obtém a entrada da tecla para quando a tecla 'R' é pressionada e solta
if (Input.GetKeyUp(KeyCode.R))
{
//call new reload function and pass the equipped item
// chama a nova função de recarga e passa o item equipado
reloadKey(m_PlayerEventHandler.EquippedItem.Get());
}
}
private void reloadKey(SavableItem itemUnderPointer)
{
int invSize = getInventory.Slots.Count;
//go through the slots, starting from past the default inventory size
// percorre os slots, começando do tamanho do inventário padrão passado
foreach (Slot slot in getInventory.Slots)
{
if (slot.CurrentItem && slot.transform.gameObject.activeInHierarchy)
{
//check that the item in the current slot has the same ammo type as the currently equipped item
// verifique se o item no slot atual tem o mesmo tipo de munição que o item atualmente equipado
if (
slot.CurrentItem.HasProperty ("Ammo Type") && slot.CurrentItem.HasProperty ("Is Ammo") &&
itemUnderPointer.HasProperty ("Ammo Type") &&
slot.CurrentItem.GetPropertyValue ("Ammo Type").String == itemUnderPointer.GetPropertyValue ("Ammo Type").String
)
{
// call the loadammo function using the item in the current slot
// chama a função loadammo usando o item no slot atual
LoadAmmo(slot, itemUnderPointer, slot.CurrentItem);
}
}
}
}
}
}
C# is case sensitive. The language sees the methods update() and Update() as two entirely different methods. The former is how you’ve written it, while the latter is how it should be written in Unity. Assuming that your MonoSingleton class isn’t doing anything screwy with Update.
You should get familiar with Debug.Log and when hitting this kind of issue you add debugging everywhere relevant. Adding a Debug.Log to “update()”, both outside and inside that “if” statement, and inside reloadKey is the very first step I would have taken to figure this issue out.
1 Like