Getting headaches from this problem, I created a simple weapon shooting script which would instantiate bullets to the pointed direction with a certain amount of force.
This bullet when it collides with certain tags it will instantiate an overlap sphere at it’s position, dealing damage to all game objects with colliders it touches. And it works, but only sometimes.
Relevant projectile code:
private void OnCollisionEnter(Collision collision)
{
//Don't count collisions with other bullets
if (collision.collider.CompareTag("Projectile")) return;
//Count up collisions
collisions++;
//Explode if bullet hits an enemy directly and explodeOnTouch is activated
if (collision.collider.CompareTag("Enemy") && explodeOnTouch) Explode();
if (collision.collider.CompareTag("DamageableNature") && explodeOnTouch) Explode();
}
private void Explode()
{
//Instantiate explosion
if (explosion != null) explosion = Instantiate(explosion, transform.position, Quaternion.identity);
//Check for enemies
Collider[] enemies = Physics.OverlapSphere(transform.position, explosionRange, whatIsEnemies);
foreach (Collider collider in enemies)
{
//Get component of enemy and DamageableNature and call Take Damage
//Just an example!
if (collider.CompareTag("Enemy"))
{
collider.GetComponent<EnemyScript>().TakeDamage(damage);
}
else if (collider.CompareTag("DamageableNature"))
{
collider.GetComponent<DamageableNature>().TakeDamage(damage);
}
}
}
Relevant Enemy code:
public int maxHealth;
[HideInInspector]
public int health;
void Start()
{
health = maxHealth;
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
private void Die()
{
Destroy(gameObject);
Debug.Log("GameObject Destroyed");
}
If I have to guess this issue is most likely from the Collider
s of the GameObject
, but after messing around with it nothing seemed to change. The shot at GameObject
will only sometimes get destroyed from certain shots.
Note: for example a damageable wall, it’s
Box Collider
is slightly bigger than the wall itself.
I would really appreciate some help or feedback on fixing this issue, or even making the code listed cleaner if needed.