Pro_Unit

RangeObserver

Nov 26th, 2021 (edited)
1,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2.  
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5.  
  6. public class RangeObserver : MonoBehaviour
  7. {
  8.     [SerializeField] private Range _range;
  9.     [SerializeField] private Transform _target;
  10.     [SerializeField] private RangeBoundary _boundary;
  11.  
  12.     public float Distance => Vector3.Distance(transform.position, Target.position);
  13.  
  14.     public UnityEvent<bool> Changed;
  15.  
  16.     private bool _value;
  17.  
  18.     public bool Value
  19.     {
  20.         get => _value;
  21.         set
  22.         {
  23.             if (value != _value)
  24.             {
  25.                 _value = value;
  26.                 Changed.Invoke(value);
  27.             }
  28.         }
  29.     }
  30.  
  31.     public Transform Target { get => _target; set => _target = value; }
  32.  
  33.     private void Start() =>
  34.         ResolveValue();
  35.  
  36.     private void ResolveValue()
  37.     {
  38.         switch (_boundary)
  39.         {
  40.             case RangeBoundary.In:
  41.                 Value = Distance.In(_range);
  42.                 break;
  43.             case RangeBoundary.Out:
  44.                 Value = Distance.Out(_range);
  45.                 break;
  46.         }
  47.     }
  48.  
  49.     private void Update() =>
  50.         Value = Distance.In(_range);
  51. }
  52.  
  53. public enum RangeBoundary
  54. {
  55.     In,
  56.     Out
  57. }
  58.  
  59. [Serializable]
  60. public struct Range
  61. {
  62.     [SerializeField] private float _min;
  63.     [SerializeField] private float _max;
  64.  
  65.     public bool In(float value) =>
  66.         _min <= value && value <= _max;
  67.  
  68.     public bool Out(float value) =>
  69.         _min >= value || value >= _max;
  70. }
  71.  
  72. public static class RangeExtensions
  73. {
  74.     public static bool In(this float value, Range range)
  75.         => range.In(value);
  76.  
  77.     public static bool Out(this float value, Range range)
  78.         => range.Out(value);
  79. }
Add Comment
Please, Sign In to add comment