Advertisement
evelynshilosky

DistanceOptimizer

Apr 26th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections.Generic;
  4.  
  5. public class DistanceOptimizer : MonoBehaviour
  6. {
  7.     public Transform player;
  8.     public float renderDistance = 100f;
  9.     public float simulationDistance = 150f;
  10.  
  11.     public List<GameObject> excludedObjects;
  12.     public List<MonoBehaviour> excludedScripts;
  13.  
  14.     private void Update()
  15.     {
  16.         if (player == null)
  17.             return;
  18.  
  19.         // Calculate the squared distances
  20.         float sqrRenderDistance = renderDistance * renderDistance;
  21.         float sqrSimulationDistance = simulationDistance * simulationDistance;
  22.  
  23.         // Find all horses and riders
  24.         GameObject[] horses = GameObject.FindGameObjectsWithTag("Horse");
  25.         GameObject[] riders = GameObject.FindGameObjectsWithTag("Rider");
  26.  
  27.         // Loop through all of the horses
  28.         foreach (GameObject horse in horses)
  29.         {
  30.             // Calculate the distance between the horse and the player
  31.             float sqrHorseDistance = (horse.transform.position - player.position).sqrMagnitude;
  32.  
  33.             // Loop through all riders
  34.             foreach (GameObject rider in riders)
  35.             {
  36.                 // Calculate the squared distance between the rider and the player
  37.                 float sqrRiderDistance = (rider.transform.position - player.position).sqrMagnitude;
  38.  
  39.                 // Determine the closest distance to the player between the horse and rider
  40.                 float sqrClosestDistance = Mathf.Min(sqrHorseDistance, sqrRiderDistance);
  41.  
  42.                 // Disable rendering if beyond render distance
  43.                 Renderer renderer = rider.GetComponent<Renderer>();
  44.                 if (renderer != null)
  45.                 {
  46.                     renderer.enabled = sqrClosestDistance <= sqrRenderDistance;
  47.                 }
  48.  
  49.                 // Disable simulation if beyond simulation distance
  50.                 foreach (MonoBehaviour script in rider.GetComponents<MonoBehaviour>())
  51.                 {
  52.                     if (script != this)
  53.                     {
  54.                         script.enabled = sqrClosestDistance <= sqrSimulationDistance;
  55.                     }
  56.                 }
  57.             }
  58.         }
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement