using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float MineSpeed = 1;
public GameObject ItemHit;
public Item ItemScript;
public RaycastHit hit;
void Start ()
{
}
void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 5))
{
ItemHit = hit.transform.gameObject;
ItemScript = ItemHit.GetComponent<Item>();
StartCoroutine(Mine());
}
}
}
IEnumerator Mine()
{
yield return new WaitForSeconds (ItemScript.ItemMiningSpeed * MineSpeed);
if (Input.GetMouseButton (0))
{
Destroy(ItemHit);
StopCoroutine(Mine());
}
}
}
This code is ment to mine the block the player looks at while holding mouse1 down.
It all works well but after the first block is mined if the player holds mouse1 down every block the player looks at gets instantly destroyed.
What you are doing here is starting a coroutine every frame that will destroy the object stored in a global variable, which also gets updated every frame, independently of the delay in your coroutine. Once the delay of the first coroutine that was started is over, every next frame the next coroutine you started will finish, resulting in blocks instantly being destroyed.
What you should do instead is define a sort of “health” property on your block class, and have that decrease every frame you are clicking on it. When it reaches 0, you destroy the block - no coroutines involved, just Update() stuff.
Also, as general advice, you shouldn’t start multiple threads for the same question.
But if you click repeatedly, you will still start multiple coroutines while the others are running. If you then hold down the mouse while the coroutines’ delays are passing, you will still mine any block that you look at instantly.
You could then stop a running coroutine when you release the mouse, but this is just not a good way of working. You can’t easily add any overlays on the block to show how close the block is to breaking, for instance, or mine it with multiple people. Going with an object based approach results in far cleaner code that is more versatile.