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;
}
}
}
}}