Minecraft like mining.

I understand the problem is there a way around it though?

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{
    public float MineSpeed = 1;

    public GameObject ItemHit;

    public Item ItemScript;


    void Start ()
    {   

    }
   
    void Update ()
    {
        StartCoroutine(playerHit());
    }

    IEnumerator playerHit()
    {   
        RaycastHit hit;   
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, 50))
        {   

            ItemHit = hit.transform.gameObject;
            ItemScript  = ItemHit.GetComponent<Item>();

            if (Input.GetMouseButton(0))
            {
                yield return new WaitForSeconds(ItemScript.ItemMiningSpeed * MineSpeed);

                if (Input.GetMouseButton(0))
                {
                    Destroy(ItemScript.ThisItem);
                }
            }
        }
    }
}

After waiting and the object is destroyed every object I look at after this while holding mouse down is destroyed instantly.

Try to start the function in the start, not in update

Bump

Bump

New code on the bump threaad

You don’t need to bump the thread the day you uploaded it, and did you read my answer?

You shouldn’t be calling StartCoroutine like that in Update.
Execution in start won’t help either as it will never be called again once it is done.

You should add some more logic to start and stop your coroutine. Also, with the current code you wouldn’t need to hold down the mouse button while the yielding takes place. You’d rather want to check the buttonDown thing frequently and if it’s not down, cancel the “mining process”.

Mining in mimecraft works like:
1.gets the mining time of the block, that you look at
2.checks if mouse is down, and looking at the same block like before
3.if yes, adds the spent time to the counter, if no, resets the timer
4.if timer reached mimingtime, resets timer, mines block.

1 Like