// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using UnityEngine.Events; namespace PixelCrushers.DialogueSystem { /// /// This component activates game objects and enables components when it receives /// OnTriggerEnter and the conditions are true, and deactivates/disables when it /// receives OnTriggerExit and the conditions are true. /// [AddComponentMenu("")] // Use wrapper. public class RangeTrigger : MonoBehaviour { /// /// The condition that must be true in order to activate/deactivate target /// game objects and components when the trigger is entered or exited. /// [Tooltip("These conditions must be true for the Range Trigger to affect GameObjects and components and invoke events")] public Condition condition; /// /// The game objects to affect. /// [Tooltip("Activate these GameObjects on trigger enter, deactivate them on trigger exit")] public GameObject[] gameObjects; /// /// The components to affect. /// [Tooltip("Enable these components on trigger enter, disable them on trigger exit")] public Component[] components; public UnityEvent onEnter = new UnityEvent(); public UnityEvent onExit = new UnityEvent(); /// /// Activates the target game objects and components if the condition is true. /// /// /// The collider that entered the trigger. /// public void OnTriggerEnter(Collider other) { if (condition.IsTrue(other.transform)) SetTargets(true); } /// /// Deactivates the target game objects and components if the condition is true. /// /// /// The collider that exited the trigger. /// public void OnTriggerExit(Collider other) { if (condition.IsTrue(other.transform)) SetTargets(false); } #if USE_PHYSICS2D || !UNITY_2018_1_OR_NEWER /// /// Activates the target game objects and components if the condition is true. /// /// /// The 2D collider that entered the trigger. /// public void OnTriggerEnter2D(Collider2D other) { if (condition.IsTrue(other.transform)) SetTargets(true); } /// /// Deactivates the target game objects and components if the condition is true. /// /// /// The 2D collider that exited the trigger. /// public void OnTriggerExit2D(Collider2D other) { if (condition.IsTrue(other.transform)) SetTargets(false); } #endif /// /// Sets the targets active/inactive. Colliders and Renderers aren't MonoBehaviours, so we /// cast them separately to access their 'enabled' properties. /// /// /// true for active, false for inactive. /// private void SetTargets(bool value) { foreach (var go in gameObjects) { if (go != null) go.SetActive(value); } foreach (var component in components) { Tools.SetComponentEnabled(component, value ? Toggle.True : Toggle.False); } if (value == true) { onEnter.Invoke(); } else { onExit.Invoke(); } } } }