Hey all, currently I’m trying to code a situation where if the player steps within the trigger collider of a tree, and presses “F”, it would start a coroutine to chop the tree.
Right now, it starts this coroutine in ALL tree objects that are created from this prefab, which is not how I want it; I only want the tree that the player is standing in the trigger of to be deleted.
I’ve been stuck on this for a few hours and I can’t seem to figure it out and I’ve exhausted google searches… I’m sure the answer is obvious but I’m a newbie
public class TreeScript : MonoBehavior
{
[SerializeField] private int treeHealth = 5;
bool isBeingChopped = false;
bool inTreeTrigger = false;
void Update()
{
if (inTreeTrigger = true && Input.GetKeyDown(KeyCode.F))
{
StartCoroutine(CoChopTree());
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
inTreeTrigger = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
inTreeTrigger = false;
}
}
private IEnumerator CoChopTree()
{
isBeingChopped = true;
WaitForSeconds waitTime = new WaitForSeconds(1f);
while (treeHealth > 0 && isBeingChopped == true)
{
treeHealth = treeHealth - 1;
Debug.Log(treeHealth);
yield return waitTime;
}
isBeingChopped = false;
Debug.Log("Stopping");
Destroy(this.gameObject, 1f);
}