Destroy object from other function

How can I destroy gameObject with other function, but in the same class ?

void OnTriggerEnter2D (Collider2D other)
    {
        if (other.tag == "Drzewo") {
            if (wyswietlenie)
                wyswietlenie = false;
            else
                wyswietlenie = true;

            }
    }

void OnGUI(){
            if (wyswietlenie) {
...
Destroy (other.gameObject)
}

P.S.
In line 15 “other” is not working becaouse is not exist in context.
I could make “public GameObject other;” and it’s work correctly
but this is not solution for me, I have many differen object to remove after collision. And I don’t imaginate to put each of them as public GameObject.

First off, there’s no need to make the variable ‘public’ if it will only be used within the same class. That’s what setting fields ‘private’ is for.

That said, that is more or less the correct approach: store the object in some field of the class, rather than trying to use a local variable in another function. Thing is, that field can’t just be a single object because you might have multiple objects. Thus you want to store your objects in a collection like a List and loop through the collection to get the individual objects, something like:

using System.Collections.Generic;

public class TestClass : MonoBehaviour {
    private List<Collider2D> colliders;
 
    void Start() {
        colliders = new List<Collider2D>();
    }
 
    void OnTriggerEnter2D (Collider2D other) {
        colliders.Add(other);
    }
 
    void OnGUI(){
        foreach (Collider2D other in colliders) {
            Destroy(other.gameObject);
        }
    }
}

Thanks a lot, it works, but I have a small problem, only one of my object can be destroyed. When I go to other object I have a got message:

“MissingReferenceException: The object of type ‘BoxCollider2D’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.”

P.S
My GUI.Box is darknes every collision during play what is wrong ?

As the error message states, you cannot destroy an object that has already been destroyed. It even suggests one fix: check if it is null before destroying it. Personally however I would say just clear the list after destroying everything in it so that the list will no longer have any destroyed objects in it. Just reinitialize the list with a new empty list after destroying everything:

    void OnGUI(){
        foreach (Collider2D other in colliders) {
            Destroy(other.gameObject);
        }
        colliders = new List<Collider2D>();
    }

Thanks for help again.