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();
}
}