1
\$\begingroup\$

I have a gameobject at a certain position in the game. I want the gameobject to be disabled once it is outside the camera's viewport, and it should become visible only when the camera focuses at that position.

\$\endgroup\$
2
\$\begingroup\$

Attach a script to the gameobject and implement the OnBecameVisible and OnBecameInvisible:

public class ExampleClass : MonoBehaviour
{
    void OnBecameInvisible()
    {
        Debug.Log("I'm not visible anymore");
    }

    void OnBecameVisible()
    {
        Debug.Log("Hey! I'm visible!");
    }
}

Keep in mind that, if you disable the gameobject, the renderers will be disabled too, and OnBecameVisible won't be called.

\$\endgroup\$
1
\$\begingroup\$

Camera.WorldToViewportPoint or WorldToScreenPoint is probably what you want. Disable the object if any coordinate if outside the "allowed" range (0-1 for viewport, 0-Screen.Width/Height for screen points). If the object is large, add a tolerance depending on size and distance.

Also, if you're just looking to improve performance, please note that frustum culling is handled by the engine by default.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.