Advertisement
LegitTeddyBears

RangeChecker

Jun 2nd, 2017
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class RangeChecker : MonoBehaviour {
  6.     //A list of tags to check for
  7.     public List<string> tags;
  8.     //List of targets that is generated when we check for what has what tags
  9.     List<GameObject> m_targets = new List<GameObject>();
  10.     //When something enters the collider
  11.     private void OnTriggerEnter(Collider other)
  12.     {
  13.         //When something enters the trigger set it as not a valid target instead of assuming that it is valid
  14.         bool invalid = true;
  15.  
  16.         for (int i = 0; i < tags.Count; i++)
  17.         {
  18.             //Check if it has any of the tags from our list if so move on to the line where it adds the object to our valid target list
  19.             if (other.CompareTag(tags[i]))
  20.             {
  21.                 invalid = false;
  22.                 break;
  23.             }
  24.         }
  25.         //If it is still invalid move on and wait for new objects to enter
  26.         if (invalid)
  27.         {
  28.             return;
  29.         }
  30.         m_targets.Add(other.gameObject);
  31.     }
  32.     //When it exits the collider
  33.     private void OnTriggerExit(Collider other)
  34.     {
  35.         for (int i = 0; i < m_targets.Count; i++)
  36.         {
  37.             //If the object leaving is a target remove it from the target list
  38.             if (other.gameObject == m_targets[i])
  39.             {
  40.                 m_targets.Remove(other.gameObject);
  41.                 return;
  42.             }
  43.         }
  44.     }
  45.     //When we say GetValidTargets we mean set the list of valid targets to the current list of targets
  46.     public List<GameObject> GetValidTargets()
  47.     {
  48.         for (int i = 0; i < m_targets.Count; i++)
  49.         {
  50.             if (m_targets[i] == null)
  51.             {
  52.                 m_targets.RemoveAt(i); i--;
  53.             }
  54.         }
  55.         return m_targets;
  56.     }
  57.     public bool InRange(GameObject go)
  58.     {
  59.         //For each object inrange check if it is in the list of valid targets
  60.         for (int i = 0; i < m_targets.Count; i++)
  61.         {
  62.             if (go == m_targets[i])
  63.             {
  64.                 //If so then return the value to be true
  65.                 return true;
  66.             }
  67.         }
  68.         //Otherwise it's false
  69.         return false;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement