- Home /
OnBecameVisible does not work
I am trying to optimize CPU usage for the game so I stop rendering when the object is out and render it again when it come back to screen. But the second part I can't get it to work. The Cat disappeared but never appeared again even I could see it in the Hierachy in editor.
The code is followed:
using UnityEngine;
public class CatUpdater : MonoBehaviour {
private CatController catController;
void Start () {
catController = transform.parent.GetComponent<CatController>();
}
void UpdateTargetPosition()
{
catController.UpdateTargetPosition();
}
void GrantCatTheSweetReleaseOfDeath()
{
Destroy( transform.parent.gameObject );
}
void OnBecameInvisible()
{
renderer.enabled = false;
catController.OnBecameInvisible();
}
void OnBecameVisible()
{
if (!renderer.enabled)
{
Debug.Log("Cat is visible " +gameObject.name);
renderer.enabled = true;
}
}
}
void OnBecameVisible()
{
if (!renderer.enabled)
{
If you can see it, make it visible?
Play around with Renderer.isVisible
@meat5000 If the camera see it and rendering was disabled then enable it. So your logic is correct. I also played around with renderer.isVisible but it also does not work.
void Update()
{
if (gameObject.renderer.isVisible && !gameObject.renderer.enabled)
{
Debug.Log("Cat is visible " +gameObject.name);
renderer.enabled = true;
}
}
The debug log never fired up.
Answer by youngexplorer · Mar 07, 2015 at 05:22 PM
Playing with the function around, I finally understood a bit more. OnBecameVisible only determine if the game object is visible ONCE. Which mean it only run the first time any camera see the object; the next time any camera sees game object, nothing will happen. So I have to repeat the function consistently to make it work in runtime.
Answer by chanfui · Apr 06, 2018 at 08:28 AM
VERY IMPORTANT -> If your Scene is visible while you're running your game, if the object / sprite is visible in your Scene window, the OnBecameVisible() will get called even if it is not visible in Game window.
Your answer
Follow this Question
Related Questions
Disabling canvas renderer optimization 4 Answers
A performance question related to setting the position of non-visible objects 1 Answer
If gameObject is invisible - disable it... what's wrong with this code? 1 Answer
Are .transform .gameObject .rigidbody component calls or just pointers? 3 Answers
'function Update' vs 'function Start {while(true)}'? 3 Answers