- Home /
[Solved] Detect if object is visible and do something if its visible?
(Sorry, maybe my English isn´t perfect)
Hi, I want to play a sound or enable a gameObject if something (a NPC) is visible (In a range), but I have no idea how to do that.
For example: If I see a zombie, which is closer than e.g. 20m a text will appear, and if he isnt visible anymore, the gameObject will be disabled again.
Thank you!
You can use Renderer.isVisible
And useful stuff includes the methods OnBecameVisible and OnBecameInvisible
You need to be clear about what you want. Distance calculations and vision calculations are not the same. Also you need to specify if you are talking about being visible to the camera (i.e. first person), or visible to another object (i.e. third person). You also need to specify if you want to detect when one object is hiding behind another.
http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html
http://docs.unity3d.com/ScriptReference/Vector3.Distance.html
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Answer by SirCrazyNugget · Jul 22, 2014 at 04:27 PM
If you want this to be able to be enabled and disabled you'll need to place a second script which handles this as once you've disabled it Update will no longer run.
void Update(){
if(renderer.isVisible && Vector3.Distance(zombie.position, player.position) <= 20f){
showText = true;
}else{
showText = false;
}
}
void OnGUI(){
if(showText){
GUI.Label("Zombie")
}
}
You could use void OnBecameVisible(){} and OnBecauseInVisible(){} to add and remove a delegate function instead of using Update to remove the small overhead though may be more trouble than it's worth.
This has the same problem as every other post I have seen so far to do with the visibility of Objects.isVisable() is dependent on all cameras rendering an object. If the object is visible from the editor window it will return true.
What about just the player view???
[Edit] I figured out a solution that worked for me. I posted the answer here:
How can I know if a gameObject is 'seen' by a particular camera?
The leading answer from @duck points you in the right direction, but it you want code have a look for my offering. I hope it helps.
Your answer

Follow this Question
Related Questions
Make object visible only for camera "X" 1 Answer
Fade Object left to right 1 Answer
Finding point of mesh visible by another game object 1 Answer
Making 3D Objects invisible 1 Answer
Know if gameObject is being seen 2 Answers