GameObject and Camera visibility

Hi,

I’m trying to write a script that allows you to interact with a gameobject, but only when it’s in the main camera view.

I’ve tried Render.IsVisible and I’m trying void OnBecomeVisible but it keeps behaving as if they are all in the camera view when they aren’t

Here is the code attached to the GameObject I want to move (to the left) on a key press but only when it’s in the camera view.

         public float leftSwipe;
public static bool isSeen;


// Use this for initialization
void Start () {

   
    isSeen = false;
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown(KeyCode.Space) && isSeen==true)
    {
        
        transform.position = new Vector3(-leftSwipe, transform.position.y, transform.position.z);
    }
    
	
}

private void OnBecameVisible()
{
    isSeen = true;
}

private void OnBecameInvisible()
{
    isSeen = false;
}

I’m not sure if I’ve completely misunderstood how the above functions work.
Thanks for any help

OnBecameVisible() and IsVisible should work, however it may not be the exact behavior you’re looking for depending on your setup, as it will include times when the object is rendered due to just its shadow being in-frame. It also will be affected by all cameras in the scene, including the scene-view camera when running in editor. I’d guess that if you aren’t receiving these messages at all, your script may not be on the same object as the Renderer (The message does not propagate up the hierarchy).

Another approach you could use would be to just calculate whether the object’s position is within the frustum of the camera. It’s quite simple to test a single point for this, though if your object is large or oblong you may run into issues where a part of the object is visible on camera but the point you are testing is not. But for simple interaction tests this may be good enough! You could just pass Camera.main to this function with your objects position.

public static bool IsWorldPositionInViewport(Vector3 worldPos, Camera cam)
{
    Vector3 viewPosition = cam.WorldToViewportPoint(worldPos);
    return viewPosition.z > 0 && viewPosition.x > 0 && viewPosition.y > 0 && viewPosition.x < 1 && viewPosition.y < 1;
}