How to use OnTriggerEnter in a script used by multiple duplicate objects?

Hello.

Is there a way for the OnTriggerEnter method to be used independently by duplicate objects using the same script? I want each of the objects to use the same OnTriggerEnter method but without creating a separate script for each. Right now the script is attached to all the duplicate objects but only gets called once.

Thanks.

I’m not sure I understand what you’re asking. Are you saying that if you have ten identical objects, and one of these objects collides with trigger X, you want to call a function on all ten objects?

Let’s say I have 10 identical block objects and a player object, I want the OnTriggerEnter method to execute for a single block when the player triggers it, even though that all 10 blocks use the same script. Here is what I have in my OnTriggerEnter method:

void OnTriggerEnter(Collider other) {
        if (other.tag == "MoveableBlock") {
            blocksLeft--;
            setBlocksLeft();
            Destroy(other.gameObject);
        }
}

Right now when the player triggers the method on a block for the first time, it runs the method fine, but when it triggers its second block, it does not decrement blocksLeft and only destroys the block.

Mark blocksLeft as static, so it’s shared between all instances, or store that information in another object all together.

1 Like

I would have another script that keeps track of the number of blocks. However…looking at this code, is this on the player?

Thank you so much. So it was not a problem with the OnTriggerEnter method but with the variable not being static to be shared among all instances of the object. I was searching for the wrong answer all along, thank you again!