Help us understand the problem. What is going on with this article?

UguiでCameraに写っているかどうか判定する

More than 1 year has passed since last update.

カメラに写っているかの判定方法は

【Unity】オブジェクトが画面外かどうかを判定する方法(まとめ)

の記事が詳しいのですが、微妙にCanvasのImageとかの場合どうすればいいのかというとあまりよいのがない。
Renderer.isVisibleやOnBecameVisible、OnBecameInVisibleやOnWillRenderObjectとかを使うのはMeshRendererとかが必要なのでuguiで使うにはびみょい。

Camera.ViewportToWorldPointを使うとよさそうだが普通にやったらGameObjectの位置になってしまうのでRectの範囲をとりたいわけです。

というわけで以下。

testVisibleCheck.cs
using UnityEngine;

public class testVisibleCheck : MonoBehaviour {

    //Uguiを表示してるカメラを貼り付ける
    [SerializeField] private Camera camera;

    private RectTransform _target;

    private Rect rect = new Rect(0, 0, 1, 1);

    public bool isVisible;

    void Start()
    {
        _target = this.GetComponent<RectTransform>();
    }

    void Update()
    {
        isVisible = rect.Contains(camera.WorldToViewportPoint(_target.transform.position + (Vector3)(_target.rect.min * _target.lossyScale.x))) ||
                   rect.Contains(camera.WorldToViewportPoint(_target.transform.position + (Vector3)(_target.rect.max * _target.lossyScale.x)));
    }

}

Canvas以下にあるGameObjectにImageでも付けてみて移動してみてください。見えなくなった(画面外)でisVisibleがfalseになります。

ただこれ、親のCanvasのrendermode設定がScreen Space Overlayだとちゃんと動きません。

テストだからUpdateに入れてるけど、毎フレームでやると重くなるかもしれないので値変更時にやるとかいいかも。uniRxだと簡単ですね。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away