Staggart

Stylized Water 2 - Configure underwater rendering through triggers

Nov 8th, 2021 (edited)
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. using StylizedWater2;
  2. using UnityEngine;
  3.  
  4. //Component requires to be added to a GameObject with a Collider (trigger checkbox enabled)
  5. public class UnderwaterTrigger : MonoBehaviour
  6. {
  7.     private const string CAMERA_TAG = "MainCamera";
  8.    
  9.     //If enabled, rendering will also be toggled based on triggers
  10.     //This way the camera can go below the (last set) water level without activating rendering (eg. stairs running down, next to a swimming pool)
  11.     public bool toggleRendering = true;
  12.    
  13.     [Space]
  14.    
  15.     public Material waterMaterial;
  16.     public float waterLevel;
  17.     public bool useTransfromForWaterlevel;
  18.  
  19.     private void Start()
  20.     {
  21.         //This is just to ensure that by default the camera is never considered underwater
  22.         UnderwaterRenderer.SetCurrentWaterLevel(-999f);
  23.  
  24.         //Making sure that the rendering is disabled until the camera first enters a trigger.
  25.         if(toggleRendering) UnderwaterRenderer.EnableRendering = false;
  26.     }
  27.        
  28.     private void OnTriggerEnter(Collider other)
  29.     {
  30.         //Note that in order for the camera to react to triggers it also needs to have a trigger on its GameObject, as well as a RigidBody component (with Kinematic enabled, so it doesn't fall)
  31.         if (!other.CompareTag(CAMERA_TAG)) return;
  32.        
  33.         if(!useTransfromForWaterlevel)
  34.         {
  35.             UnderwaterRenderer.SetCurrentWaterLevel(waterLevel);
  36.         }
  37.         //Or use the transform's Y-position
  38.         else
  39.         {          
  40.             UnderwaterRenderer.SetCurrentWaterLevel(this.transform);
  41.         }
  42.        
  43.         //You can leave the material field empty, in case every water body uses the same material anyway, just at different water levels
  44.         if(waterMaterial) UnderwaterRenderer.SetCurrentWaterMaterial(waterMaterial);
  45.  
  46.         if (toggleRendering) UnderwaterRenderer.EnableRendering = true;
  47.     }
  48.  
  49.     private void OnTriggerExit(Collider other)
  50.     {
  51.         if (!other.CompareTag(CAMERA_TAG)) return;
  52.        
  53.         if (toggleRendering) UnderwaterRenderer.EnableRendering = false;
  54.     }
  55. }
Add Comment
Please, Sign In to add comment