Skip to content

Instantly share code, notes, and snippets.

@hpcergar
Created March 29, 2022 19:48
Show Gist options
  • Save hpcergar/62819bff96f5c1d6422f51e9c061985d to your computer and use it in GitHub Desktop.
Save hpcergar/62819bff96f5c1d6422f51e9c061985d to your computer and use it in GitHub Desktop.
Unity: check if an object is visible for the main camera
using UnityEngine;
public class Example : MonoBehaviour
{
// Cache variables
Camera cameraInstance;
Transform currentTransform;
// State
bool wasVisible = false;
private void Start()
{
this.cameraInstance = Camera.main;
this.currentTransform = this.gameObject.GetComponent<Transform>();
}
private void Update()
{
bool isCurrentlyVisible = this.IsVisible();
if(this.HasBecomeVisible(isCurrentlyVisible)) {
Debug.Log("Now is visible");
} else if (this.HasBecomeInvisible(isCurrentlyVisible)) {
Debug.Log("Now is invisible");
}
this.wasVisible = isCurrentlyVisible;
}
// Idea from https://stackoverflow.com/a/46365015/2814721
private bool IsVisible()
{
// We could use any Gameobject's transform here instead of this.currentTransform
Vector3 position = this.cameraInstance.WorldToViewportPoint(this.currentTransform.position);
return position.x > 0 && position.x < 1 && position.y > 0 && position.y < 1;
}
private bool HasBecomeVisible(bool isVisible)
{
return false == this.wasVisible && isVisible;
}
private bool HasBecomeInvisible(bool isVisible)
{
return true == this.wasVisible && false == isVisible;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment