Problem with prefabs with same script are all triggering a coroutine at the same time

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 :frowning:

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);
    }

Can you show us the entire script?

I’ve updated it to show the entire script, thank you for taking a look.

Your problem is here: if (inTreeTrigger = true
You use == to compare, not =. The way you have it now you are setting that to true every frame in every copy of the script.

Better yet you don’t need that comparison at all, since == true is never necessary. You can just write that line simply as if (inTreeTrigger && Input.GetKeyDown(KeyCode.F))

I’m an idiot. Thank you.