OnBecameInvisible() Throwing error when game stops

Hello, I tried and searched but did not found any solution to my problem. I call OnBecameInvisible() function from few different scripts. All of them are throwing errors. First one is this part of code:

void OnBecameInvisible(){
     if (transform.position.x < Camera.main.transform.position.x) {
          //do stuff
     }
}

It says “Assertion failed on expression: ‘go.IsActive() && go.GetTag() != 0’”. This happens only when I exit play mode.

And there is another error on second line of this code:

void OnBecameInvisible(){
     if (transform.position.x < playerTransform.position.x) {
          //do stuff
     }
}

It says: “MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.” It happens whenever I exit the play mode. I had my Scene tab closed but nothing.

What should I do?

Do some null checking, it’s almost free.

void OnBecameInvisible(){
      if (transform != null && transform.position.x < Camera.main.transform.position.x) {
           //do stuff
      }
 }

void OnBecameInvisible(){
      if ((transform != null && playerTransform != null) && transform.position.x < playerTransform.position.x) {
           //do stuff
      }

}

if it’s null it will not evaluate the second expression