Skip to content

Instantly share code, notes, and snippets.

@dunnston
Created April 4, 2024 11:31
Show Gist options
  • Save dunnston/1f42e7476c3fc3f3dabf2b712813e40d to your computer and use it in GitHub Desktop.
Save dunnston/1f42e7476c3fc3f3dabf2b712813e40d to your computer and use it in GitHub Desktop.
Unity scripts for picking up items and adding to inventory
using UnityEngine;
using MoreMountains.InventoryEngine;
namespace MoreMountains.InventoryEngine
{
public class InteractableItemPicker : MonoBehaviour
{
public InventoryItem Item; // The item that will be picked and added to the inventory.
public int Quantity = 1; // The quantity of the item to be added upon pickup.
public bool PickableIfInventoryIsFull = false; // Allows picking the item even if the inventory is full.
public bool DisableObjectWhenDepleted = false; // Disables the object when the item has been fully picked.
public bool RequirePlayerTag = true; // Requires the colliding object to have the "Player" tag.
private Inventory _targetInventory; // The target inventory to which the item will be added.
private string playerID = "Player1"; // Assuming a default player ID for simplicity.
public InteractableItemPicker interactableItemPicker;
protected virtual void Start()
{
Initialization();
}
protected virtual void Initialization()
{
_targetInventory = Inventory.FindInventory(Item.TargetInventoryName, playerID);
if (_targetInventory == null)
{
Debug.LogError("InteractableItemPicker: Target inventory not found.");
}
else
{
Debug.Log("InteractableItemPicker: Target inventory found.");
}
}
public bool Pickable()
{
// With the given API, we'll attempt to add the item to check if it's pickable.
bool wasAbleToAdd = _targetInventory.AddItem(Item, 0); // Attempt to add zero quantity to check.
if (!wasAbleToAdd)
{
Debug.Log("InteractableItemPicker: Inventory is full or item cannot be added.");
return false;
}
return true;
}
public void Pick()
{
Debug.Log("Attempting to pick up the item.");
// Attempt to add the item to the inventory and capture the result.
bool wasAdded = _targetInventory.AddItem(Item, Quantity);
// Log the result of the attempt.
Debug.Log($"Attempted to add {Item.ItemName} (ID: {Item.ItemID}) to inventory. Success: {wasAdded}");
if (wasAdded)
{
Debug.Log($"Successfully added {Quantity} of {Item.ItemName} to inventory.");
if (DisableObjectWhenDepleted)
{
gameObject.SetActive(false);
Debug.Log($"InteractableItemPicker: {gameObject.name} has been disabled after picking.");
}
}
else
{
Debug.LogError($"Failed to add {Item.ItemName} to inventory. Check if the inventory is full or if the item meets all criteria for being added.");
}
}
}
}
using UnityEngine;
using System.Collections;
using MoreMountains.Tools;
using MoreMountains.InventoryEngine;
using MoreMountains.Feedbacks;
namespace MoreMountains.TopDownEngine
{
/// <summary>
/// This script allows an item to be picked up interactively by pressing the "E" key when the player is within range.
/// It is meant to be attached to a pickable item GameObject.
/// </summary>
public class InteractablePickableItem : MonoBehaviour
{
public MMFeedbacks PickedMMFeedbacks; // Feedbacks to play when the item gets picked.
public bool DisableColliderOnPick = false; // Determines if the item's collider should be disabled upon pickup.
public bool DisableObjectOnPick = true; // Determines if the item should be disabled (hidden) upon pickup.
public float DisableDelay = 0f; // Delay before disabling the item, allowing for animations or sounds to play.
public bool DisableModelOnPick = false; // Determines if the item's visual model should be disabled upon pickup.
public GameObject Model; // The visual model of the item.
public bool RequireCharacterComponent = true; // Item can only be picked by characters.
public bool RequirePlayerType = true; // Item can only be picked by player characters.
private Collider _collider; // The Collider component of the item.
private Collider2D _collider2D; // The Collider2D component of the item.
private GameObject _collidingObject; // The GameObject that is currently colliding with the item.
private bool _playerInRange = false; // Flag to indicate if the player is in range for interaction.
private InteractableItemPicker _itemPicker = null; // The InteractableItemPicker component attached to the item.
private WaitForSeconds _disableDelay; // WaitForSeconds used for delaying the disable action.
protected virtual void Start()
{
// Initialization of components and settings.
_disableDelay = new WaitForSeconds(DisableDelay);
_collider = gameObject.GetComponent<Collider>();
_collider2D = gameObject.GetComponent<Collider2D>();
_itemPicker = gameObject.GetComponent<InteractableItemPicker>();
PickedMMFeedbacks?.Initialization(this.gameObject);
}
protected virtual void Update()
{
// Check for the "E" key press to initiate the pickup process if the player is in range.
if (_playerInRange && Input.GetKeyDown(KeyCode.E))
{
Debug.Log($"Attempting to pick up item: {gameObject.name}");
PickItem(_collidingObject);
}
}
public virtual void OnTriggerEnter2D(Collider2D collider)
{
// Detect if the player has entered the trigger zone.
if (collider.CompareTag("Player"))
{
_playerInRange = true;
_collidingObject = collider.gameObject;
Debug.Log("Player has entered pickup range.");
}
}
public virtual void OnTriggerExit2D(Collider2D collider)
{
// Detect if the player has exited the trigger zone.
if (collider.CompareTag("Player"))
{
_playerInRange = false;
_collidingObject = null;
Debug.Log("Player has exited pickup range.");
}
}
protected virtual void PickItem(GameObject picker)
{
// Check if the item is pickable first
if (_itemPicker != null && _itemPicker.Pickable())
{
// Play any defined effects
Effects();
// Trigger the PickableItemEvent
// PickableItemEvent.Trigger(this, picker);
// Log the pick action
Debug.Log("InteractableItemPicker: Pick method called.");
// Call the Pick method on the _itemPicker
_itemPicker.Pick();
// Disable the collider if configured to do so
if (DisableColliderOnPick)
{
if (_collider != null) _collider.enabled = false;
if (_collider2D != null) _collider2D.enabled = false;
}
// Disable the model if configured to do so
if (DisableModelOnPick && (Model != null))
{
Model.SetActive(false);
}
// Finally, disable the GameObject if configured to do so
if (DisableObjectOnPick)
{
StartCoroutine(DisableObjectCoroutine());
}
}
else
{
// If the item is not pickable or _itemPicker is null, log a warning or error.
if (_itemPicker == null)
{
Debug.LogError("ItemPicker component reference is missing.");
}
else
{
Debug.Log("Item is not pickable at the moment.");
}
}
}
protected IEnumerator DisableObjectCoroutine()
{
// Coroutine for delaying the disabling of the item.
yield return _disableDelay;
gameObject.SetActive(false);
Debug.Log($"Item disabled: {gameObject.name}");
}
protected void Effects()
{
// Example: Playing a feedback when the item is picked up
PickedMMFeedbacks?.PlayFeedbacks();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment