11using System.Collections;
12using System.Collections.Generic;
28 [Tooltip(
"Dispatched when close enough to a target.")]
36 [Tooltip(
"The interval in seconds at which to check this detector's conditions.")]
43 [Header(
"Detector Targets")]
44 [Tooltip(
"The list of target objects.")]
54 [Tooltip(
"Objects with this tag are added to the list of targets.")]
58 [Tooltip(
"Use a Layer instead of the target list.")]
60 [Tooltip(
"The Layer containing the objects to check.")]
69 [Header(
"Distance Settings")]
70 [Tooltip(
"The target distance in meters to activate the detector.")]
79 [Tooltip(
"The distance in meters at which to deactivate the detector.")]
95 [Tooltip(
"Draw this detector's Gizmos, if any. (Gizmos must be on in Unity edtor, too.)")]
98 private IEnumerator proximityWatcherCoroutine;
99 private GameObject _currentObj =
null;
109 proximityWatcherCoroutine = proximityWatcher();
111 GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(
TagName);
112 List<GameObject> targets =
new List<GameObject>(taggedObjects.Length +
TargetObjects.Length);
116 for (
int t = 0; t < taggedObjects.Length; t++) {
117 targets.Add(taggedObjects[t]);
124 StopCoroutine(proximityWatcherCoroutine);
125 StartCoroutine(proximityWatcherCoroutine);
129 StopCoroutine(proximityWatcherCoroutine);
133 IEnumerator proximityWatcher(){
134 bool proximityState =
false;
135 float onSquared, offSquared;
139 if(_currentObj !=
null){
140 if(distanceSquared(_currentObj) > offSquared){
142 proximityState =
false;
147 if(nearby.Length > 0) {
148 _currentObj = nearby[0].gameObject;
149 proximityState =
true;
155 if (distanceSquared(target) < onSquared) {
156 _currentObj = target;
157 proximityState =
true;
169 yield
return new WaitForSeconds(
Period);
173 private float distanceSquared(GameObject target){
174 Collider targetCollider = target.GetComponent<Collider>();
176 if(targetCollider !=
null){
177 closestPoint = targetCollider.ClosestPointOnBounds(transform.position);
179 closestPoint = target.transform.position;
181 return (closestPoint - transform.position).sqrMagnitude;
185 void OnDrawGizmos() {
188 Gizmos.color =
Color.green;
190 Gizmos.color =
Color.red;
192 Gizmos.DrawWireSphere(transform.position,
OnDistance);
193 Gizmos.color =
Color.blue;
194 Gizmos.DrawWireSphere(transform.position,
OffDistance);
206 [System.Serializable]
virtual void Deactivate()
virtual void OnValidate()
GameObject[] TargetObjects
ProximityEvent OnProximity