I have a problem with inherite OnTriggerEnter2D.

Hi! I’m new in Unity and I’m learning right now. It’s possible I’m doing something stupid, so sorry in advance.

What I actually try to do is call OnTriggerEnter2D in the inherit class and also call it in the class is inherited. But for some reason the OnTriggerEnter2D of the inherited class is it called twice (I used a variable to count to prove it), I don’t know why is callining two times when is triggered.

My code is this:

public class Resource : MonoBehaviour
{
    public int number;

    protected virtual void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player") && other.isTrigger && (playerWeapon.initialValue == breakeble.initialValue))
        {
        //I count with this the number of times this is triggered, for now this count 2 every time
            number++;
        }
    }
    }
public class Tree : Resource
{
    protected Animator anim;


    private void Start()
    {
        anim = GetComponent<Animator>();
    }
    protected override void OnTriggerEnter2D(Collider2D other)
    {
        base.OnTriggerEnter2D(other);
       
    }
  

}

Like you can see this is super basic code, I deleted everything trying to find the error, without luck.

I’m not sure why this happens, but try this:
Rename you virtual method to not conflict with the Unity method name which Unity calls, and from the unity method in the base class invoke your virtual method.

Thanks for answer me. Yes, I was looking for something like that, but finally I found my error. Like I predicted the error was really dumb, I was forgetting I was using that script in an object that has two BoxCollider. I needed to first check if the BoxCollider was a trigger, if not the two BoxColliders activate my script, that was the problem. Je, sorry…

1 Like