- Home /
Question by
Kirbsssys · Oct 11, 2021 at 01:19 AM ·
collisioncollideritem pickup
I want to know how to wait before I can pick up something
Here's my pickup code for my 2 items
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemPickup : MonoBehaviour
{
public Inventory inventory;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Rock")
{
inventory.rockAmount += 1;
Destroy(other.gameObject);
}
if (other.tag == "Log")
{
inventory.logAmount += 1;
Destroy(other.gameObject);
}
}
}
And I want to know how to make it wait like 3 seconds before being able to pick up an item if I grabbed the other item
Comment
Answer by Eno-Khaon · Oct 11, 2021 at 01:55 AM
If we assume that you want to be able to sit on another item until you're allowed to pick it up, it might look something like this:
public float pickupInterval = 3f;
// This can be set to -pickupInterval in Start() instead, based on preference
float lastPickupTime = Mathf.negativeInfinity;
// Check every frame, in case player is sitting on a pickup
void OnTriggerStay(Collider other)
{
// If it's been at least interval-seconds since last pickup...
if(Time.time - lastPickupTime > pickupInterval)
{
// Processes faster than ([tag] == "string")
if(other.CompareTag("rock"))
{
inventory.rockAmount += 1;
lastPickupTime = Time.time;
Destroy(other.gameObject);
}
else if(other.CompareTag("Log"))
{
// etc.
}
}
}
Answer by Nick123451 · Oct 11, 2021 at 02:19 AM
I'm no expert on the best way to do this but I will give it a shot. Let me know if this works.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemPickup : MonoBehaviour
{
public Inventory inventory;
[SerializeField] private float delay = 3.0f; // this is the wait time
private float timer = 0;
private bool isPickingUp = false;
private void OnTriggerEnter(Collider other)
{
// if you aren't currently picking something up
if (!isPickingUp)
{
if (other.tag == "Rock")
{
inventory.rockAmount += 1;
Destroy(other.gameObject);
isPickingUp = true; // you are now picking something up
}
if (other.tag == "Log")
{
inventory.logAmount += 1;
Destroy(other.gameObject);
isPickingUp = true; // you are now picking something up
}
}
}
private void Update()
{
Timer();
}
private void Timer()
{
// if you pick up item
if (isPickingUp)
{
// timer increases gradually
timer += Time.deltaTime;
// if timer becomes greater than the delay
if (timer > delay)
{
// you have finished picking up item
isPickingUp = false;
// reset the timer
timer = 0;
}
}
}
}