Advertisement
Guest User

ObjectLayerCulling

a guest
May 9th, 2023
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ObjectLayerCulling : MonoBehaviour
  6. {
  7. private Camera mainCamera;
  8. private List<GameObject> taggedObjects;
  9.  
  10. private void Start()
  11. {
  12. mainCamera = Camera.main; // get the main camera
  13. taggedObjects = new List<GameObject>(GameObject.FindGameObjectsWithTag("Objects")); // find all objects with the tag "Objects"
  14. }
  15.  
  16. private void Update()
  17. {
  18. foreach (GameObject obj in taggedObjects)
  19. {
  20. if (obj == null)
  21. {
  22. continue; // skip to the next object if this one is null
  23. }
  24.  
  25. // Check if object is within camera view
  26. Vector3 screenPoint = mainCamera.WorldToViewportPoint(obj.transform.position);
  27. bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1;
  28.  
  29. // If object is not within camera view, deactivate it
  30. if (!onScreen)
  31. {
  32. // Check if any part of the mesh is visible on screen
  33. Renderer renderer = obj.GetComponent<Renderer>();
  34. if (renderer != null)
  35. {
  36. bool isVisible = GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(mainCamera), renderer.bounds);
  37. if (isVisible)
  38. {
  39. obj.SetActive(true);
  40. }
  41. else
  42. {
  43. obj.SetActive(false);
  44. }
  45. }
  46. }
  47. // If object is within camera view, activate it
  48. else
  49. {
  50. obj.SetActive(true);
  51. }
  52. }
  53. }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement