- Home /
my projectile is supposed to destroy itself after it deals damage
I have a projectile that hit a game object with the tag "enemy" and hit the box collider and deal damage which works butter it deals damage the projectile is supposed to destroy itself which is not so I'm quite sure where my mistake is. Also when my projectile hits the collider it spawns a partly system but it spawns a duplicate every time it hits the collider so I feel like this problem will be solved by solving the 1st problem.
this is my projectile script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
private Transform target;
public float speed = 70f;
public GameObject impactEffect;
public int damage = 10;
public float explosionRadius = 0f;
public void Seek(Transform _target)
{
target = _target;
}
// Update is called once per frame
void Update()
{
if (target == null)
{
Destroy(gameObject);
return;
}
Vector3 dir = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
if (dir.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
transform.Translate(dir.normalized * distanceThisFrame, Space.World);
transform.LookAt(target);
}
void HitTarget()
{
GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(effectIns, 1f);
if (explosionRadius > 0f)
{
Explode();
}
else
{
Damage(target);
Destroy(effectIns);
}
}
void Explode()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach (Collider collider in colliders)
{
if (collider.tag == "Enemy")
{
Damage(collider.transform);
Debug.Log("I Got Hit");
}
}
}
void Damage(Transform enemy)
{
Enemy e = enemy.GetComponent<Enemy>();
if (e != null)
{
e.TakeDamage(damage);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
}
@jjdoughboy I answered this specific question for you in your previous thread -- https://answers.unity.com/questions/1720731/im-working-on-a-tower-defense-game-and-my-enemy-ga.html
Aren't duplicate post not allowed on here like most tech forums? This should be flagged..
Answer by FZ_Applications · May 08, 2020 at 08:50 PM
Just call Destroy(gameObject); in the Damage method to destroy the projectile.