Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ObjectLayerCulling : MonoBehaviour
- {
- private Camera mainCamera;
- private List<GameObject> taggedObjects;
- private void Start()
- {
- mainCamera = Camera.main; // get the main camera
- taggedObjects = new List<GameObject>(GameObject.FindGameObjectsWithTag("Objects")); // find all objects with the tag "Objects"
- }
- private void Update()
- {
- foreach (GameObject obj in taggedObjects)
- {
- if (obj == null)
- {
- continue; // skip to the next object if this one is null
- }
- // Check if object is within camera view
- Vector3 screenPoint = mainCamera.WorldToViewportPoint(obj.transform.position);
- bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1;
- // If object is not within camera view, deactivate it
- if (!onScreen)
- {
- // Check if any part of the mesh is visible on screen
- Renderer renderer = obj.GetComponent<Renderer>();
- if (renderer != null)
- {
- bool isVisible = GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(mainCamera), renderer.bounds);
- if (isVisible)
- {
- obj.SetActive(true);
- }
- else
- {
- obj.SetActive(false);
- }
- }
- }
- // If object is within camera view, activate it
- else
- {
- obj.SetActive(true);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement