Unity PR

【Unity】オブジェクトが見えているかどうかを判別する方法

記事内に商品プロモーションを含む場合があります

この記事では、特定のオブジェクトがカメラに写っているかどうかを判別する方法を解説します。

使用したUnityのバージョン
  • Unity 2021.3.23f1

OnBecameVisible() と OnBecameInvisible()

OnBecameVisible()OnBecameInvisible()MonoBehaviour のコールバックの一種で以下のような特徴があります。

  • 可視状態、または不可視状態になった際に呼び出される
  • エディタ上のシーンに表示されていても見える扱いとなる
  • Renderer が必要
  • OnBecameInvisible() は見えていた状態から見えなくなった場合のみ処理される

例えば、以下のようなコードを Renderer が付いているオブジェクトにアタッチするだけで簡単に見えているか判別することができます。

using UnityEngine; public class Visible : MonoBehaviour { public bool IsVisivle { get; private set; } private void OnBecameVisible() { IsVisivle = true; } private void OnBecameInvisible() { IsVisivle = false; } }

また、オブジェクトが見えてない時(カメラに写ってない時)に enable = false とすることで計算量を減らして軽くすることができる。

RendererのisVisible

RendererisVisible は、可視状態ではtrue、不可視状態ではfalseを返します。

  • エディタ上のシーンに表示されていても見える扱いとなる
  • Renderer が必要

見えているときにupdateなどで連続で処理をさせたりできます。

using UnityEngine; public class Square : MonoBehaviour { private SpriteRenderer _spriteRenderer; void Start() { _spriteRenderer = GetComponent<SpriteRenderer>(); } void Update() { if(_spriteRenderer.isVisible) { Debug.Log("見えている"); } else { Debug.Log("見えていない"); } } }