Make script work only within a collider?

I was wondering the best route to make a function work in the bounds of a collider. OnStayCollider and EnterCollider are always updating and performance hitters, and wanted to make the function only work within a collider, and after the Input is called.

In here, the function “Update” calls for the Input, and “FindsclosestEnemy” is the one im looking to reduce only to a collider. For Now its doing a check in the whole map.

Thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.Experimental.Rendering.Universal;

public class LockOn : MonoBehaviour {

private CharMovementBehaviour m_xMove;
private GameObject m_xPlayer;
private GameObject Enemy;
GameObject [] enemy;
private Transform playerpos;
GameObject closest;
private GameObject CloseEnemyInstance;
Vector2 target;

private HealthModule health;


bool bIsDead = false;


 //CursorLockMode lockMode;

//[SerializeField] private GameObject mark;
//private Transform markplace;

// public float speed;

bool isLockingOn = false;

//bool mouselook = false;

    GameObject FindClosestEnemy() 
    {
        enemy = GameObject.FindGameObjectsWithTag("Enemy");
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in enemy) {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            if(curDistance< distance)
            {
                closest = go;
                distance = curDistance;
            }
        }
        return closest;
    }

void Locking(GameObject enemy){

   
   
         
      

        Vector3 target = CloseEnemyInstance.transform.position;
        m_xPlayer = GameUtil.xGetPlayer();
        playerpos = m_xPlayer.GetComponent<Transform> ();
        Vector2 ppos = playerpos.transform.position;
        m_xMove = m_xPlayer.GetComponent<CharMovementBehaviour>();
        

       
        



     float dist = Vector2.Distance (target, ppos);
    if (dist <= 30 ){
   m_xMove.vInstantFacePoint(target);
  // Mouse.current.WarpCursorPosition(target);
   
  //  float step = speed * Time.deltaTime;

       // markplace = mark.GetComponent<Transform> ();
       // Vector3 markpos = markplace.transform.position;
       // markpos = Vector3.MoveTowards(markpos, target, step);

   
}
      }



   // Cursor.lockState = CursorLockMode.Locked;
    
   private void Update()
   {
    Cursor.visible = true;
    Cursor.lockState = CursorLockMode.None;
    
    
   
   {
      if (Input.GetKeyDown(KeyCode.Tab) ){
        
        
        CloseEnemyInstance = FindClosestEnemy();


        isLockingOn = !isLockingOn;
    }
    if(isLockingOn)
    {

    if (CloseEnemyInstance != null){

      Locking(Enemy);
      Cursor.visible = false;

    }

    health = CloseEnemyInstance.GetComponent<HealthModule>();

         bIsDead = !bIsDead;
    
         if ( health.bIsDead() )
        //CloseEnemyInstance = null;

         {
         isLockingOn = false;
         

    
      
    
    
     // Cursor.lockState = CursorLockMode.Locked;


    }
    }
}


}}


    

I initially thought this was straight forward but then, which “if” ?

if you need stuff to only run after contact or while in contact have a boolean set by enter/stayleave and then if it is in the right condition do that code else not.

Sorry my bad. I meant the function working only within the collider, not the whole map.

I do have to add what you said in the second line, but also reduce the function to work only on the radius of the collider too.

right… and as I said, if its inside the collider your boolean is true so does stuff, if not it doesnt…

There are many approaches to this, really depends on what your working with and what the scale is.

If the targets have colliders, the simplest approach is to use spherecast(3D)/circlecast(2D) to detect those within a radius. If you plan to scale up to more than a few hundred active targets, colliders could become a performance issue.

If there isn’t very many targets and no colliders, you could keep a list of them and iterate through it checking if their distance is within your desired radius. I think this is partially what your doing right now by checking the whole map, just add a maximum distance.

If you want thousands of targets you will need something custom (like a hashmap grid) that doesn’t use colliders. This tutorial is an advanced solution, but the general idea is sound. I use something similar for an RTS game to handle ~5000 units detecting each other.

Thought of another one I have used
If your targets have colliders and rigidbodies, put a trigger collider on the detector. In your script use OnTriggerEnter, OnTriggerExit to Add/Remove from a list. In your FindsclosestEnemy function, just check that list. I think raycasting is probably better for what you are doing though. You don’t need to keep track of everything in range all the time, you just need to know once, when FindclosestEnemy is called.

Thanks to you both, i used a combination of methods and now the script works only within the collider, and when is in presence of said collider.