Basic Timer with added functions in the future

So basically I have this extremely basic script… It’s set to a tree game object, and when I click the tree it adds the item to my inventory, then destroys the tree. What I want it to do is have a timer on it so when I click on it has a “random” chance to obtain the tree within, lets say, a 5 second period. If it fails it keeps the object on the playing field, and you will get another chance to chop down the tree. However, I want to be able to expand on to it in the future when I implement a progress bar for this process.I’m not asking for you to code my game. Guidance, or an example script would be fine. Any help would be greatly appreciated, thanks! :slight_smile:

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            inventory.AddItem(0);
            Destroy(gameObject);
        }
    }

Tried this way, but when I click it doesn’t actually countdown and add it to my inventory. Any suggestions?

public class PickUp : MonoBehaviour
{

    Inventory inventory;
    public float timeRemaining = 10f;

    // Use this for initialization
    void Start()
    {

        inventory = GameObject.Find("Inventory").GetComponent<Inventory>();

    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            if (timeRemaining > 0)
            {
                Debug.Log("Waitting..." + timeRemaining);
                timeRemaining -= Time.deltaTime;
                if (timeRemaining == 0) { inventory.AddItem(0); Destroy(gameObject); }
            }

        }

    }
}

This is what I do when I want to delay actions

bool inProgress;
float duration;
float finishTime;

void Begin(){
    if(inProgress) return;
    inProgress = true;

    finishTime = Time.time + duration;
}

void Update(){
    if(Time.time >= finishTime){
        Action();
        inProgress = false;
    }
}

This is really convenient for checking if the time has come. If you want to make a progress bar, it’s also pretty simple to compute how filled it should be. The formula being something like this:

float fillAmount = 1f - (finishTime - Time.time)/duration;
  1. Compute the remaining time and divide it by the duration.
  2. Subtract it from 1 to get the time already spent.

For the last thing you wanted to do, the random chance. I found the best way to do randomness is by using this function:

bool Chance(float chance){
    float roll = UnityEngine.Random.Range(0f, 1f);
    return (roll < chance);
}

It’s very simple and intuitive. Just choose a number from 0 to 1, where 0 means 0% chance and 1 means 100% chance.

void Action(){
    // 30 % chance
    if(Chance(0.3f)){
        inventory.AddItem(0);
    }
}