0

In Unity I have this piece of code :

var go = gameObject;
var some=123;
Debug.Log(go);
socket.On("login", _ => {
    Debug.Log("1");
    Debug.Log(some);
    Debug.Log(go);
    Debug.Log("2");
});

Simply I want to access the variable go, but as that is outside the closure and type of GameObject, it can't be accessed.

In the console :

HomeObject
1
123

But everything after calling that HomeObject disappears.

How can I access my own class/gameObject in the closure?

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86

1 Answers1

0

Keep that object above in the hierarchy.

If I am not mistaken your GameObject is being destroyed before than callback from the socket.

You can check that by loging:

....

socket.On("login", _ => {
            Debug.Log("Socket callback");
        });

void OnDestroy()
    {
        Debug.Log("Called before than send callback");
        //if destroyed you can't access `gameObject`
        //keep the object above in the calling hierarchy, or cancel request.
    }