IF statement running twice?

I’m a beginner and I’m trying to get this code to check if an object collides with the player, and then have it do other things and then destroy the object. For some reason it keeps running twice? (No the script isnt on the object twice and no the code isn’t repeated)
Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FallingNotes : MonoBehaviour
{
    public List<GameObject> list = RandomRhythm.randomRhythm;
    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            Debug.Log(gameObject.GetInstanceID());
            //if (list.Count > 0 && gameObject.tag == list[0].tag)
            //{
            //    Debug.Log(list[0].tag);
            //    Destroy(list[0]);
            //    list.Remove(list[0]);
            //}
            Destroy(gameObject);
        }
        if (collision.gameObject.layer == 6)
        {
            Destroy(gameObject);
        }
    }
}

1 Like

Please show full class.

If it’s in a collision responder function, it could run multiple times in case of bounce, or in case there is more than one collider hitting.

Use a boolean and set it, then test it to make sure it only runs once.

1 Like

Would that still happen if the gameObject gets destroyed though? Because it is supposed to destroy the GameObject on contact, yet is still running twice

1 Like

If you read the documentation on Destroy() you will note a discussion of when destruction actually takes place. Hint: it isn’t immediately.

1 Like

Awesome, thanks. your bool suggestion works, is there a neater way to do it or is that just the only way to make it work?

There is always an infinite number of ways to accomplish things in software, as well as an even broader range of opinions as to which one is “neater” or less neat.

If your problem is solved, move on. Nobody gets extra points for noodling “neater” solutions.