how exactly does OnBecameVisible() and OnBecameInvisible() work ?

hey Guys I generate a Level for my Game based on tiles and a png. The Background gets moved, and so it lags a lot, if there is a lot of tiles. so I decided to use OnBecameInvisible() and OnBecameVisible(). but somehow it doesnt work for me :/.
this is the script on all the Objects:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class activechecker : MonoBehaviour {

    void OnBecameVisible()
    {
        enabled = true;
    }

    void OnBecameInvisible()
    {
        enabled = false;
    }

    public void Disable()
    {
        enabled = false;
    }
}

on generation I call Disable, so the Tiles are not there on the beginning, however that does not work. notice, that these are the examples from the official Unity Docs.

var tile = Instantiate(colormapping.prefab, position, Quaternion.identity, transform);
                tile.GetComponent<activechecker>().Disable();

can someone help ? :slight_smile: is enabled too old and I should use setactive ?
thanks in advance

OnBecameVisible and OnBecameInvisible are tricky because they use all cameras in the editor, including the scene editing camera. So make sure the scene view is hidden, or the scene view camera is facing away from the actual scene, or the functions won’t appear to work.

You should probably also be using SetActive() on the GameObject itself.

3 Likes

Ya, depending on your goal there… ‘enabled’ means the component (in your example - it means the script is enabled or not… not the game object).

Thank you for explaining this, GroZZleR. I was pulling my hair out trying to figure out why OnBecameInvisible wasn’t working with a Cinemachine virtual camera and it was because my scene view was pulled absurdly far back, keeping everything visible. Zooming in in the scene view “fixed” my problem :slight_smile:

2 Likes