becauseBecause the method Instantiate has side effects, It will create a gameobjectgame object on your scene. You can check them in the hierarchy tab to find it.
So you don't actually lose the reference to the button component. The local variables arevariable holding a reference to it is indeed discarded, but that's okay, because the scene hierarchy still holds a reference to it (you can access it via FindObjectsOfType() or methods that traverse the scene hierarchy).
By the way, some statements in the post are not quite correct:
It's said that local variable is deallocated (lost) when leaving the countaining method.
It's said that local variable is deallocated (lost) when leaving the containing method.
Firstly, when does the 'deallocating' occur? It's not 'when leaving the countainingcontaining method' but 'when leaving it's scope'.
And doare all local variable isvariables deallocated or lost directly? It depends on the type of variable.
There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data. They are stored in Heap and Stack Memory respectively.
When a value type variable is discarded, it will be recycled directly. If a reference type variable is discarded, the data it referenced will keepstill persist in memory. If it is not referenced by any object in the next garbage collection pass, it will be deleted.(markMark-and-sweep-algorithm) The variable holding its reference is discarded, but the actual object is still in heap memory. If other objects still hold its referencereferences to it, then it won't be cleaned up.