- Home /
I have a specific problem with my trigger
I am sort of new with Unity, and I am making my first game currently. Sorry if I seem like a noob. I have been using triggers, but I cant seem to get this specific part to work.
void OnTriggerStay(Collider col)
{
if (col.gameObject.tag == "Enemy" || col.gameObject.tag == "FastEnemy" || col.gameObject.tag == "TankEnemy")
{
EnemyCoords = col.gameObject.transform.position;
transform.parent.GetComponentInChildren<MGTURRET>().EnemyCoords = EnemyCoords;
Debug.Log(col.gameObject.tag);
}
else
{
Debug.Log("Not Colliding");
transform.parent.GetComponentInChildren<MGTURRET>().Firing = false;
Shooting = false;
}
}
This is part of my code for a turret that I have made. It locks on to the nearest enemy, and shoots at it. The turret starts shooting when an object with one of those tags enters the trigger, but I want it to stop shooting when there is no object with those tags colliding with the trigger. It is weird because when I test the game out, the debug log always says "Not Colliding", even though it is colliding with an enemy, and the debug log also says that it is colliding with enemies. Isn't anything under the 'else' supposed to run if none of the conditions are met above? It is still running everything below the 'else', even though the conditions above are met. So it is basically acting like it is colliding with an enemy and not colliding with an enemy at the same time. I am stumped.
have you tried using col.CompareTag("Enemy") ins$$anonymous$$d of col.gameObject.tag == "Enemy" ?
Answer by Cornelis-de-Jager · Apr 04, 2018 at 01:09 AM
Try this:
void OnTriggerStay(Collider col)
{
if (col.gameObject.tag == "Enemy" || col.gameObject.tag == "FastEnemy" || col.gameObject.tag == "TankEnemy")
{
EnemyCoords = col.gameObject.transform.position;
transform.parent.GetComponentInChildren<MGTURRET>().Firing = true;
transform.parent.GetComponentInChildren<MGTURRET>().EnemyCoords = EnemyCoords;
Debug.Log(col.gameObject.tag);
}
}
void OnTriggerExit (Collider col) {
Debug.Log("Not Colliding");
transform.parent.GetComponentInChildren<MGTURRET>().Firing = false;
Shooting = false;
}
Answer by Hunty_Guy · Apr 04, 2018 at 01:23 AM
Well, I actually have something extremely similar in my code already.
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Enemy" && Shooting == true)
{
transform.parent.GetComponentInChildren<MGTURRET>().Firing = false;
Shooting = false;
}
}
}
That works perfectly if the enemy exits the trigger, but the turret keeps shooting if the enemy dies in the trigger. I am hoping to actually get rid of this OnTriggerExit if I can get the OnTriggerStay to detect if an enemy isnt colliding with the trigger.