0
\$\begingroup\$

In the script below, "btn" is a local variable in OnEnable() method. It's said that local variable is deallocated (lost) when leaving the countaining method. Why this one (btn) is not ? Nb: when the game is running and Button is clicked (OnClick) method is called

using UnityEngine.ui;
List<Button> _answers;
public List<Button> Answers { get { return _answers; } }
[SerializeField] Button buttonPrefab;

private void OnEnable()
{
    CreateAnswerButtonPool();
    
    for (int i = 0; i < Answers.Count; i++)
    {
        Button btn = Answers[i];
        btn.onClick.AddListener(() => OnClick(btn));
    }
}

 private void CreateAnswerButtonPool()
{
    _answers = new List<Button>();

    for (int i = 0; i < 5; i++)
    {
        Button bt = Instantiate(buttonPrefab, buttonsparent.transform) as Button;
        bt.gameObject.SetActive(false);
        _answers.Add(bt);
    }
}

void OnClick(Button btn)
{
    //.....
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Because the method Instantiate has side effects, It will create a game object on your scene. You can check the hierarchy tab to find it.

So you don't actually lose the button component. The local variable 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 containing method.

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

And are all local variables 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 still persist in memory. If it is not referenced by any object in the next garbage collection pass, it will be deleted.(Mark-and-sweep-algorithm) The variable holding its reference is discarded, but the actual object is still in heap memory. If other objects still hold references to it, then it won't be cleaned up.

\$\endgroup\$
1

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.