Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created April 5, 2018 19:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unity3dcollege/6ef46e95bc789f34b07589a4554e4ef4 to your computer and use it in GitHub Desktop.
Save unity3dcollege/6ef46e95bc789f34b07589a4554e4ef4 to your computer and use it in GitHub Desktop.
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class HoldToPickup : MonoBehaviour
{
[SerializeField]
[Tooltip("Probably just the main camera.. but referenced here to avoid Camera.main calls")]
private Camera camera;
[SerializeField]
[Tooltip("The layers the items to pickup will be on")]
private LayerMask layerMask;
[SerializeField]
[Tooltip("How long it takes to pick up an item.")]
private float pickupTime = 2f;
[SerializeField]
[Tooltip("The root of the images (progress image should be a child of this too)")]
private RectTransform pickupImageRoot;
[SerializeField]
[Tooltip("The ring around the button that fills")]
private Image pickupProgressImage;
[SerializeField]
private TextMeshProUGUI itemNameText;
private Item itemBeingPickedUp;
private float currentPickupTimerElapsed;
private void Update()
{
SelectItemBeingPickedUpFromRay();
if (HasItemTargetted())
{
pickupImageRoot.gameObject.SetActive(true);
if (Input.GetButton("Fire1"))
{
IncrementPickupProgressAndTryComplete();
}
else
{
currentPickupTimerElapsed = 0f;
}
UpdatePickupProgressImage();
}
else
{
pickupImageRoot.gameObject.SetActive(false);
currentPickupTimerElapsed = 0f;
}
}
private bool HasItemTargetted()
{
return itemBeingPickedUp != null;
}
private void IncrementPickupProgressAndTryComplete()
{
currentPickupTimerElapsed += Time.deltaTime;
if (currentPickupTimerElapsed >= pickupTime)
{
MoveItemToInventory();
}
}
private void UpdatePickupProgressImage()
{
float pct = currentPickupTimerElapsed / pickupTime;
pickupProgressImage.fillAmount = pct;
}
private void SelectItemBeingPickedUpFromRay()
{
Ray ray = camera.ViewportPointToRay(Vector3.one / 2f);
Debug.DrawRay(ray.origin, ray.direction * 2f, Color.red);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 2f, layerMask))
{
var hitItem = hitInfo.collider.GetComponent<Item>();
if (hitItem == null)
{
itemBeingPickedUp = null;
}
else if (hitItem != null && hitItem != itemBeingPickedUp)
{
itemBeingPickedUp = hitItem;
itemNameText.text = "Pickup " + itemBeingPickedUp.gameObject.name;
}
}
else
{
itemBeingPickedUp = null;
}
}
private void MoveItemToInventory()
{
Destroy(itemBeingPickedUp.gameObject);
itemBeingPickedUp = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment