Skip to main content
2 of 4
added 1222 characters in body
Mangata
  • 2.8k
  • 1
  • 4
  • 10

because the method Instantiate has side effects, It will create a gameobject on your scene. You can check them in the hierarchy tab.

So you don't actually lose the reference to the button component. The local variables are indeed discarded, but that's okay.

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. 

Firstly, when does the 'deallocating' occur? It's not 'when leaving the countaining method' but 'when leaving it's scope'.

And do all local variable is 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 Stack and Heap Memory respectively.

When a value type variable is discarded, it will be recycled directly. If a reference type variable is discarded, it will decrement the reference count. They are managed by garbage collection. The variable holding its reference is discarded, but the actual object is still in memory. If other objects still hold its reference then it won't be cleaned up.

Mangata
  • 2.8k
  • 1
  • 4
  • 10