hi everyone:) i’m trying to make a simple 3d tower defense. my tower (a cylinder) has a Capsule collider attached to it with a larger radius so that it can detect if an enemy has entered its area. the enemy, on the other hand, is made of three parts (simply animated). all of these are trigger and the main part of the enemy has a rigidbody. my problem is: all he towers i build in the lower section of my ground work perfectly fine, instead in the upper part of the space (nearby the “castle” whch is not touched by the trigger area anyway) the towers fire up to 5/6 times to the same enemy. how come?
this is the script of my tower:
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
public GameObject bulletPrefab;
void OnTriggerEnter(Collider co) {
if(co.GetComponent<Monster>()) {
print ("triggered");
Instantiate(bulletPrefab, transform.position, Quaternion.identity);
bulletPrefab.GetComponent<Bullet>().target = co.transform;
}
}
}
Edit: randomly it happens also in the lower section and i’ve also noticed that sometimes when the enemy is in front of the tower nothing happens, but when it’s outside of range, it fires the bullet(s).
how could i do it? i mean how could i make it that the tower “knows” that that monster has already been shot and cannot shoot THAT one again and instead focus on the next one? the way i’ve used the booleans until now prevents the tower from shooting more than once, after a single bullet, the trigger never sets true again (even if i set so that when that bullet is destroyed the bool is false again). hope i made my self clear enough… thanks!
The problem is that as far as i know, on triggerexit is called whenever the collision stops taking place and in this case the enemy is still in the tower’s area. Does it stop the collision if i say ontriggerexit even if the enemy is still in the collision area? Cause that would solve the problem. Or if that’s not possibile i would like also to make it so that if the enemy is where it can be shot, the bullet is created (even 2 or 3 times) but right now it just starts an awful number of shots one after another and it makes the game incredibly annoying and boring. Plus there’s this weird bug that a bullet is randomly spawned also from turrets that cannot have “collided” with any enemy… Maybe there’s something im missing and i should start all over
You should try put you enemy triggers on different layers and make your tower detect trigger event only from one of the layer (probably trigger on main body of enemy). this way you might have single TriggerEnter call on your tower.
Change the layer of Rigidbody to the enemy-body layer as well.