- Home /
How to use isVisible or OnBecameInvisible() to detect player offscreen
This is probably a dumb question but I can't figure it out. I need to detect if the player is offscreen and then call some events. Here is some code I was testing:
 public class GameHandler : MonoBehaviour
 {
     public Renderer playerRenderer;
     private void Update()
     {
         if (playerRenderer.isVisible)
         {
             print("Player is onscreen");
         }
 
         if (!playerRenderer.isVisible)
         {
             print("Player is offscreen");
         }
     }
 }
When I run this I get "Player is onscreen" all the time, even when the player is offscreen. I never get "Player is offscreen" under any circumstance. I also tried this code instead, on the player renderer.
 public class PlayerOffscreen : MonoBehaviour
 {
     public void OnBecameVisible()
     {
         print("Player is onscreen");
     }
     public void OnBecameInvisible()
     {
         print("Player is offscreen");
     }
 }
When I run this I get "Player is onscreen" once at game start, regardless of whether the player is actually onscreen. I don't get any other messages until I stop the game and then I get "Player is offscreen" once.
I have heard that the editor camera can interfere with these functions so in both cases I have it turned completely away from the scene. It doesn't seem to make a difference.
What am I doing wrong?
Answer by ArminAhmadi · Sep 17, 2020 at 05:47 PM
I'm not sure what exactly you mean by on screen and off screen but check this and see if it's what you want.
 private void OnApplicationPause(bool pause)
 {
     if (pause)
     {
         OnBecameInvisible();
     }
     else
     {
         OnBecameVisible();
     }
 }
 private void OnBecameVisible()
 {
     print("Player is onscreen");
 }
 private void OnBecameInvisible()
 {
     print("Player is offscreen");
 }
Your answer
 
 
             Follow this Question
Related Questions
OnBecameVisible Invisible working with sorting layers 0 Answers
OnBecameVisible and OnBecameInvisible with LOD group. 2 Answers
Activate Game object when in Camera view and deactivate when out of camera view. 2 Answers
How to properly use Renderer.OnBecameInvisible for Culling objects off screen? 2 Answers
why the function OnBecameVisible and OnBecameInvisible doesn't work in canvas renderer ? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                