Unity获取相机渲染范围内的所有物体

2024-01-07 21:30:36

1.获取所有相机渲染的物体(包括子物体)。?

using System.Collections.Generic;
using UnityEngine;

public class RenderedObjects : MonoBehaviour
{
    public Camera camera;

    private void Start()
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
    }

    private void Update()
    {
        Renderer[] renderers = GetRenderedObjects(camera);
        foreach (Renderer renderer in renderers)
        {
            Debug.Log("Rendered object: " + renderer.gameObject.name);
        }
    }

    private Renderer[] GetRenderedObjects(Camera camera)
    {
        Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
        Renderer[] allRenderers = FindObjectsOfType<Renderer>();
        List<Renderer> renderedObjects = new List<Renderer>();

        foreach (Renderer renderer in allRenderers)
        {
            if (GeometryUtility.TestPlanesAABB(frustumPlanes, renderer.bounds))
            {
                renderedObjects.Add(renderer);
            }
        }

        return renderedObjects.ToArray();
    }

}

2.获取所有相机渲染的物体(不包括子物体)。?

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class RenderedObjects : MonoBehaviour
{
    public Camera camera;

    private void Start()
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
    }

    private void Update()
    {
        Transform[] parentObjects = GetParentObjects(camera);
        foreach (Transform parentObject in parentObjects)
        {
            if (parentObject != null) Debug.Log("Parent object: " + parentObject.gameObject.name);
        }
    }

    private Transform[] GetParentObjects(Camera camera)
    {
        Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
        Renderer[] allRenderers = FindObjectsOfType<Renderer>();
        HashSet<Transform> parentObjects = new HashSet<Transform>();

        foreach (Renderer renderer in allRenderers)
        {
            if (renderer.transform.childCount == 0 && GeometryUtility.TestPlanesAABB(frustumPlanes, renderer.bounds))
            {
                parentObjects.Add(renderer.transform);
            }
            else if (renderer.transform.childCount > 0)
            {
                Transform parent = renderer.transform.parent;
                while (parent != null)
                {
                    if (!parentObjects.Contains(parent) && GeometryUtility.TestPlanesAABB(frustumPlanes, parent.GetComponent<Renderer>().bounds))
                    {
                        parentObjects.Add(parent);
                    }
                    parent = parent.parent;
                }
            }
        }

        return parentObjects.ToArray();
    }

}

文章来源:https://blog.csdn.net/a451319296/article/details/135392750
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。