Advertisement
Pro_Unit

TriggerTagActions

Dec 11th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3.  
  4. using UnityEngine;
  5. using UnityEngine.Events;
  6.  
  7. namespace GameCore
  8. {
  9.     [RequireComponent (typeof (Collider))]
  10.     public class TriggerTagActions : MonoBehaviour
  11.     {
  12.         private Collider _collider = null;
  13.         public new Collider collider { get { if (_collider == null) _collider = GetComponent<Collider> (); return _collider; } }
  14.         private void Awake () { collider.isTrigger = true; }
  15.  
  16.         [SerializeField] List<TagAction> OnEnterTrigger;
  17.         [SerializeField] List<TagAction> OnExitTrigger;
  18.         public void AddOnEnterAction (string Tag, UnityEventGameObject action)
  19.         {
  20.             TagAction tagAction = new TagAction ();
  21.             tagAction.Tag = Tag;
  22.             tagAction.action = action;
  23.             OnEnterTrigger.Add (tagAction);
  24.  
  25.         }
  26.         public void AddOnExitAction (string Tag, UnityAction<GameObject> action)
  27.         {
  28.             var tagAction = OnExitTrigger.Find (ta => ta.Tag == Tag);
  29.             if (tagAction == null) return;
  30.             tagAction.action.AddListener (action);
  31.         }
  32.  
  33.         private void OnTriggerEnter (Collider other)
  34.         {
  35.             foreach (var trigger in OnEnterTrigger)
  36.                 trigger.Invoke (other.gameObject);
  37.         }
  38.  
  39.         private void OnTriggerExit (Collider other)
  40.         {
  41.             foreach (var trigger in OnExitTrigger)
  42.                 trigger.Invoke (other.gameObject);
  43.         }
  44.     }
  45.  
  46.     [System.Serializable]
  47.     public class TagAction
  48.     {
  49.         public string Tag;
  50.         public UnityEventGameObject action;
  51.         public void Invoke (GameObject go)
  52.         {
  53.             if (go.CompareTag (Tag))
  54.                 action.Invoke (go);
  55.         }
  56.     }
  57.     [System.Serializable] public class UnityEventGameObject : UnityEvent<GameObject> { }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement