Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Collections;
- /// <summary>
- /// This culls all the objects which are child objects of the current object, that have a mesh renderer.
- /// This is much more efficient than attaching a cullObject to each individual object.
- /// </summary>
- public class CullChildObjects : MonoBehaviour
- {
- private MeshRenderer[] meshes;
- private Camera playerCamera;
- private bool outOfDistanceLastFrame;
- void Start ()
- {
- // attempt to get the camera controlled by the player
- playerCamera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();
- if (playerCamera == null)
- print ("The main camera was not found inside CulledObject script.");
- meshes = GetComponentsInChildren<MeshRenderer> ();
- // attempt to get the meshRenderer component on the child objects
- if (meshes == null || meshes.Length == 0) {
- print (tag);
- print ("CullChildObjects require a mesh component on child objects, in order to enable and disable the objects.");
- }
- }
- void Update ()
- {
- // calculate the absolute distance between the camera and this object
- var distance = Math.Abs (Vector3.Distance (transform.position, playerCamera.transform.position));
- // if the distance between the objects is above the render distance
- if (distance > CulledObject.RenderDistance && !outOfDistanceLastFrame)
- OnObjectOutOfDistance ();
- else if (distance < CulledObject.RenderDistance && outOfDistanceLastFrame) // if we're in distance and we were not last frame
- OnObjectInDistance ();
- }
- /// <summary>
- /// Called when the object is out of the distance of the camera - and it was in distance last frame.
- /// </summary>
- void OnObjectOutOfDistance ()
- {
- outOfDistanceLastFrame = true;
- for (int i = 0; i < meshes.Length; i++)
- if (meshes [i] != null && meshes [i].enabled)
- meshes [i].enabled = false;
- }
- /// <summary>
- /// Called when the object is in distance of the camera - and it was not in distance last frame.
- /// </summary>
- void OnObjectInDistance ()
- {
- outOfDistanceLastFrame = false;
- for (int i = 0; i < meshes.Length; i++)
- if (meshes [i] != null && !meshes [i].enabled)
- meshes [i].enabled = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement