Variable value doesn't change

What I’m trying to do is add +1 to a variable whenever an object (red cube) becomes invisible.

The problem is that the variable gets +1 only once.

No error message displayed. What’s wrong with my code?


CODE: using System.Collections;using System.Collections.Generic;using UnityEngine; -

You can make variable int x; static. This way, everytime you instantiate a new
CubeScript it’ll get your desired x value. Also, as @myzzie mentioned , you are resetting the value to 0 on Start()

OnBecameInvisible is a message sent to the game object bearing the Renderer leaving the Camera’s frustum.

It needs a Renderer, the Renderer needs to leave the Camera’s frustum.

So, if your object leaves and re-enters the camera’s frustum, it should add 1 to the variable every time it leaves it.
Did you mean to have more than one object with only one variable?

You are setting the value to 0 in Start() every time you instantiate a new instance.

Try to do this:

void OnBecameInvisible() {
     x = x+1;