I’m making a Tower Defense game. My Towers/Turrets currently know if they can shoot an enemy if the enemy triggers OnTriggerEnter(). I then code it so it focuses that enemy until it the enemy dies.
The problem comes in when the target dies. Because I’m triggering off of OnTriggerEnter() to start shooting, the other enemies entered range long ago and don’t trigger it anymore. They never get shot at. My solution is to go through a list of bools for each enemy per frame (or five) and check if their inrange = true and fire if so. inrange will be set by OnTriggerEnter().
How do I store the OnTriggerEnter() bool on each instance, and then access those every frameto determine if there is something left to shoot? I’m doing it this way because I think accessing bools is much more efficient than checking to see which enemy is nearest every frame (or five). Please correct me if I’m wrong and I’ll do it the easy way.
public class Turret : MonoBehaviour {
public GameObject Bulletprefab;
public float rotationspeed = 35;
bool inrange = false;
GameObject targetplayer;
float attackrate = 0.5f;
float nextattack = 0;
public int attackstr = 10;
GameObject lockedon;
// Update is called once per frame
void Update()
{
// Rotate turret fancy-like
transform.Rotate(Vector3.up * Time.deltaTime * rotationspeed, Space.World);
// Find cloest player and lockon until it's dead, if it isn't already lockedon to another player
if (!lockedon)
{
targetplayer = FindClosestPlayer();
lockedon = targetplayer;
}
// If lockedon to a target, attack
if (lockedon)
{
// If player is in range (OnTriggerEnter), attack
if (inrange)
{
// *****HOW DO I CHECK IF targetplayer's inrange VARIABLE == TRUE HERE?*****
Attack();
}
}
}
void OnTriggerStay(Collider co)
{
if (co.tag =="Player")
{
//***** HOW DO I SET THE SPECIFIC PLAYER INSTANCE inrange VARIABLE TO TRUE HERE INSTEAD?*****//
inrange = true;
Debug.Log(targetplayer);
}
}
void OnTriggerExit(Collider co)
{
// If it uncollides with an Enemy, set inrange false
if (co.tag == "Player")
{
//***** HOW DO I SET THE SPECIFIC PLAYER INSTANCE inrange VARIABLE TO False HERE INSTEAD?*****//
inrange = false;
Debug.Log("Uncollided with:");
Debug.Log(co.tag);
}
}