- Home /
Activate object if visible and Deactivate object if invisible
Hi
I have a Main Camera. And I want to deactivate object if they aren't visible by the Main Camera. And if it is. Then it activate
Someone who can help me?
I tried a lot
Like this.
function OnBecameInvisible ()
{
gameObject.SetActive (false);
}
Please help. Thanks in advance
Answer by TheValar · Oct 21, 2013 at 05:47 PM
Vector3 position = camera.WorldToViewportPoint(transform.position);
if(position.x<0||position.x>1||position.y<0||position.y>1){
OnBecameInvisible()}
I think that should do it.
p.s. sorry for the horrible formatting I'm using an ancient browser.
EDIT: Ok I feel dumb as I now realize that OnBecameInvisible() is a method of the Renderer class. I'm now confused about what the problem is. Is the method not firing when the object moves out of view?
I copy/paste your code and Unity gives me this errror
Assets/Scripts/scr_s1ingame/Destroy$$anonymous$$ap.js(1,8): UCE0001: ';' expected. Insert a semicolon at the end.
and
Assets/Scripts/scr_s1ingame/Destroy$$anonymous$$ap.js(4,20): UCE0001: ';' expected. Insert a semicolon at the end.
It's more like pseudo-code really just to give you an idea of the logic you are after. But off the top of my head try adding a semicolon after the OnBecameInvisible() call and change Vector3 to var since it's in javascript.
@androids Sorry to be blunt but if you don't know what to do about " UCE0001: ';' expected. Insert a semicolon at the end." then I'm afraid you may be a little out of your depth. Try some tutorials. Get more experience program$$anonymous$$g.
Your example code works when I try it, so deactivating works fine. The problem is, once it has been deactivated, for all intents and purposes it no longer exists. It will not become visible when its position is in the camera frustum since... it's no longer active! And there is no collider to test for using this method. You can reactivate it manually once the camera is pointed at its location again, and once it is again active it should fire off IsBecameVisible, because it just became visible after being reactivated.
What is it exactly that you're trying to do? There should be some other way of achieving our desired results.
What I exactly try to do is to deactivate (gameObject.SetActive(false);) 50 gameobjects if they're invisible in the $$anonymous$$ain Camera without using Occlusion Culling. If it's visible in the $$anonymous$$ain Camera, it should activate etc.
Answer by crazysurge · Oct 22, 2013 at 02:02 AM
if your trying to make an object invisble do this renderer.enabled = false then set a boolean